Currently, my restAPI and my App are both hosted on XAMPP. My restAPI url is laravel.dev.
My POST route looks as so...
Route::post('/content', 'Test#save');
and my Controller...
class Test extends Controller
{
public function save()
{
return "here";
}
}
Pretty simple, but now I want to make a POST request to this route from my App. I am trying to that using react's fetch, but I do not know what URL to put since my attempt does not work...
fetch('laravel.dev', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
});
I don't care about passing anything to the route, I just want a successful call to the restAPI server. Right now I'm getting...
POST http://localhost/App/src/laravel.dev 404 (Not Found)
That is also the wrong path as well, as /App is my app and I am trying to call the restAPI server.
What do I need to change to make a successful call?
fetch needs a protocol. Right now it tries to request a "local" resource. Also, add your endpoint:
fetch('http://laravel.dev/content', {
// ...
});
Related
I am creating a simple CRUD operations in laravel by using Vue js along with vue axios and vue router.
Routing is working fine as expected but the issue is when i have save the data by using axios the response i get is 401 unauthorized.
I have protected my route just like this in web.php
Route::get('/{any}', function () {
return view('posts');
})->where('any', '.*')->middleware(['auth']);
And in api.php i have routes like this.
Route::post('/quiz/create-quiz-category', 'QuizCategoryController#store')->middleware(['auth']);
I am currently using laravel default auth system.
Below is my vue component script code.
this.axios.post(uri, {post: this.post}, {
headers: {
'x-csrf-token': document.querySelectorAll('meta[name=csrf-token]')[0].getAttributeNode('content').value,
'Accept' : 'application/json'
}
}).then((response) => {
// this.$router.push({name: 'home'});
});
I appreciate if someone tell me that what wrong with code, and i am not currently using any passport or jwt.
Thanks.
api_token: this.user.api_token
axios.post("http://foo",
{headers: { 'Authorization' : 'Bearer '+ api_token}})
.then(response => {
//action
})
link: https://forum.vuejs.org/t/401-unauthorized-vuejs-laravel-and-passport/59770
or
postComment() {
axios.post('/api/posts/'+this.post.id+'/comment', {
api_token: this.user.api_token,
body: this.commentBox
})
but make sure that you have "user.api_token"
I created a webapi in ASP.NET Core, and I need to consume it using React, the web api works normally, if I use curl or postman among others, it works normally. The problem starts when I'm going to use React, when I try to make any requests for my API with js from the problem.
To complicate matters further, when I make the request for other APIs it works normally, this led me to believe that the problem was in my API, but as I said it works with others only with the react that it does not. I've tried it in many ways.
The API is running on an IIS on my local network
Attempted Ways
Using Ajax
$ .ajax ({
method: "POST",
url: 'http://192.168.0.19:5200/api/token',
beforeSend: function (xhr) {
xhr.setRequestHeader ("Content-type", "application / json");
},
date: {
name: 'name',
password: 'password'
},
success: function (message) {
console.log (message);
},
error: function (error) {
/ * if (error.responseJSON.modelState)
showValidationMessages (error.responseJSON.modelState); * /
console.log (error);
}
});
Using Fetch
const headers = new Headers ();
headers.append ('Content-Type', 'application / json');
const options = {
method: 'POST',
headers,
body: JSON.stringify (login),
mode: 'cors' // I tried with cors and no-cors
}
const request = new Request ('http://192.168.0.19:5200/api/token', options);
const response = await fetch (request);
const status = await response.status;
console.log (response); * /
// POST adds a random id to the object sent
fetch ('http://192.168.0.19:5200/api/token', {
method: 'POST',
body: JSON.stringify ({
name: 'name',
password: 'password'
}),
headers: {
"Content-type": "application / json; charset = UTF-8"
},
credentials: 'same-origin'
})
.then (response => response.json ())
.then (json => console.log (json))
Using Request
var request = new XMLHttpRequest ();
request.open ('POST', 'http://192.168.0.19:5200/api/token', true);
request.setRequestHeader ('Content-Type', 'application / json; charset = UTF-8');
request.send (login);
ERRORS
Console
Network tab
When I do this without being change the content type to JSON it works
because the API returns saying that it is not a valid type.
Apart from allowing CORS in you .NET configuration. You also need to return 200 OK for all OPTION requests.
Not sure how it's done in .NET but just create a middleware that detects the METHOD of the request, and if it's OPTIONS, the finish the request right there with 200 status.
Well I had the same issue and it seems that you need to add the action to the HttpPost attribute in the controller.
Here is an example.
[HttpPost("[action]")]
public void SubmitTransaction([FromBody] SubmitTransactionIn request)
{
Ok();
}
Try like this
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(option => option.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials());
app.UseAuthentication();
app.UseMvc();
}
I'm trying to use fetch api with laravel, but the request goes to the login url, not the given url.
for example;
route
//also this route group has auth and admin middlewares (checks user is authenticated and is admin)
Route::delete("media/delete/{id}", ["as" => "admin.posts.media.delete", "uses" => "AdminController#deletePostMedia"]);
ajax
fetch("../../media/delete/" + id, {
method: "DELETE",
headers: new Headers({
"X-CSRF-TOKEN": document.head.querySelector("[name=csrf-token]").content
})
})
it gives me the below error:
DELETE http://commerce.test/login 405 (Method Not Allowed)
as you can see above, the request goes to login url, not given url..
How can I fix this?
Laravel by default includes axios for ajax requests and it's very easy to use, have a look here.
In your example you'd write something like this:
axios.delete('/media/delete/' + id)
.then(response => {
console.log(response.data);
})
.catch(error=> {
console.log(error);
});
I have been doing React JS a while, but only front-end. Now I would like to spice it up with external data. So I tried with AXIOS / FETCH unfortunatelly both of them produced this miserable result. Here is the challenge:
fetch("http://localhost:8080/backend/datatest/src.json", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Hubot',
login: 'hubot',
})
})
fetch('http://localhost:8080/backend/datatest/src.json')
.then(function(response) {
return response.json()
}).then(function(json) {
console.log(json)
})
Its basicly a copy-paste from GITHUB of fetch, assuring nothing would go badly. "GET" function works perfectly, but i got problems with POST-ing. I keep getting back the same error mesage
POST http://localhost:8080/backend/datatest/src.json 404 (Not Found)
HOWEVER! GET works perfectly.
I am using React JS, Redux, node JS. This JSON file didnt get installed at any server. In your opinion what would be the next step.
Regards,
Koppany
I'm developing a Node app using Express, Mongoose and Backbone with Marionette.
All routes are working well except the delete route.
If I call this.model.destroy, I always get this error:
DELETE http://localhost:3000/api/user 404 (Not Found)
The 404 is returned in Express's delete route, like if Express didn't support it, but I've seen numerous examples across the web using it.
Here's my setup:
Mongoose Schema:
var UserSchema = new mongoose.Schema(
{
name: String,
email: String,
age: Number
});
User = mongoose.model('User', UserSchema);
ExpressJS Route: (not working)
app.del('/api/user/:id', user.remove);
OR
app.delete('/api/user/:id', user.remove);
This route is called by backbone model.destroy(), but returns error 404.
ExpressJS user.js controller: (works but is not reached because of the 404 before)
exports.remove = function(req, res)
{
var id = req.params.id;
User.findById(req.params.id, function(err, user)
{
user.remove(function(err)
{
if(err) res.json(err);
res.json('all good');
});
});
};
BackboneJS Model
var User = Backbone.Model.extend({
idAttribute: "_id",
url: '/api/user/',
});
BackboneJS client View
var UserView = Backbone.Marionette.ItemView.extend(
{
template: Handlebars.compile($('#userView').html()),
events:
{
'click .delete-button': 'deleteUser'
},
deleteUser: function(event)
{
this.model.remove();
}
});
I always get this error:
DELETE http://localhost:3000/api/user 404 (Not Found)
HOWEVER it works if I use this direct ajax call:
jQuery.ajax({
url:'/api/user/' + this.model.id,
type: 'DELETE',
success:function(data, textStatus, jqXHR)
{
}
});
So, why does this work if I call the route via Ajax, if Backbone internally also uses Ajax? Why does Backbone fail to make such a simple model.destroy()?
Is there a way to configure Backbone Model.destroy method to work well like the Ajax example above? Thanks
Found the problem. Backbone model.remove() was not sending the id because I was using "url" in this way:
Backbone.Model.extend({
url: '/users',
//...
});
That will tell Backbone to use exactly /users as the URL for all actions.
To ensure sending the id using "url", one can use a function:
url: function() {
return '/list_items/' + encodeURIComponent(this.id)
}
Or even better use "urlRoot" instead of "url", let the default "url" function add the id:
urlRoot: '/users'
Working like a charm with urlRoot