问题
I am currently making a POST
request to my laravel API using the following code...
fetch('http://laravel.dev/content', {
method: 'POST',
mode:'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*'
},
body: JSON.stringify({
})
})
.then((response) => {
console.log(response);
});
The route looks as follows...
Route::post('/content', array('middleware' => 'cors', 'uses' => 'Test@save'));
Although I have configured cors
mode, I am actually using no-cors
.
My controller Test@save
looks like...
class Test extends Controller
{
public function save()
{
echo "here";
}
}
I am trying to send the string here
back to the fetch request. But in my fetch request, when I do console.log(response)
, I get the following response...
Response {type: "opaque", url: "", status: 0, ok: false, statusText: "" ...}
Is there any way to send a custom response using my Laravel route? If so, how do I do so?
回答1:
You can try as:
public function save()
{
return response()->json(['data' => 'here']);
}
The json method will automatically set the
Content-Type
header toapplication/json
, as well as convert the given array into JSON using the json_encode PHP function.
Docs
回答2:
You are almost there. You must return another promise, that gets text or json from fetch:
fetch('http://laravel.dev/content', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
})
})
.then((response) => response.text()) //or response.json()
.then((text) => {
console.log(text);
});
Also, you need to make a cors request, otherwise you can't access the response. You'll need to add this global middleware to laravel if you want to accept ajax requests from all origins
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS')
->header('Access-Control-Allow-Headers', 'content-type');
}
}
Read This article on global middleware.
来源:https://stackoverflow.com/questions/40616588/create-a-custom-response-from-laravel-using-fetch-api