使用获取API从laravel创建自定义响应 [英] Create a custom response from laravel using fetch API

查看:30
本文介绍了使用获取API从laravel创建自定义响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

路线如下...

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

尽管我已经配置了 cors 模式,但实际上我正在使用 no-cors .

Although I have configured cors mode, I am actually using no-cors.

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

My controller Test@save looks like...

class Test extends Controller
{

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

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

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: "" ...}

有什么方法可以使用我的Laravel路由发送自定义响应吗?如果是这样,我该怎么办?

Is there any way to send a custom response using my Laravel route? If so, how do I do so?

推荐答案

您可以尝试以下方式:

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

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

The json method will automatically set the Content-Type header to application/json, as well as convert the given array into JSON using the json_encode PHP function.

文档

这篇关于使用获取API从laravel创建自定义响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆