使用fetch API从laravel创建自定义响应

时间:2016-11-15 17:56:24

标签: laravel reactjs fetch

我目前正在使用以下代码向我的laravel API发出POST请求...

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);
    });

路线如下......

Route::post('/content', array('middleware' => 'cors', 'uses' => 'Test@save'));

虽然我已配置cors模式,但实际上我使用的是no-cors

我的控制器Test@save看起来像......

class Test extends Controller
{

    public function save() 
    {
       echo "here";
    }
}

我正在尝试将字符串here发送回获取请求。但是在我的获取请求中,当我执行console.log(response)时,我得到以下响应...

Response {type: "opaque", url: "", status: 0, ok: false, statusText: "" ...}

有没有办法使用我的Laravel路线发送自定义回复?如果是这样,我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以尝试:

public function save() 
{
    return response()->json(['data' => 'here']);
}
  

json方法会自动将Content-Type标头设置为application/json,并使用json_encode PHP函数将给定数组转换为JSON。

Docs

答案 1 :(得分:1)

你快到了。你必须返回另一个promise,它从fetch获取text或json:

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);
});

此外,您需要提出cors请求,否则您无法访问响应。如果要接受来自所有来源的ajax请求,则需要将此全局中间件添加到laravel

<?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');
    }
}

在全球中间件上阅读This article