繁体   English   中英

Angular HTTP发布不接受JSON响应?

[英]Angular HTTP post not accepting JSON response?

我在laravel中创建了一个API,并在邮递员中对其进行了测试,它运行良好。 但是当我从角度尝试时,它可以很好地返回字符串文本,但不能返回JSON响应

我在互联网上搜索它,发现设置了content-type:application / json,并尝试了以各种方式在标头中设置内容类型,但是问题仍然存在

    var obj = JSON.parse('{"email":"ab@gm.com","password":"12345678"}');
    //1st type of header
    var headers_object = new HttpHeaders().set('Content-Type', 
    'application/json');

     const httpOptions = {
         headers: headers_object
     };

    //2nd type of header
        var HTTPOptions = {
            headers: new HttpHeaders({
               'Accept':'application/json',
               'Content-Type': 'application/json'
            }),
            'responseType': 'application/json' as 'json'
         }

        return this.http.post<any>(`http://127.0.0.1:8000/api/auth/login`, obj,HTTPOptions ).subscribe(resp => {
            console.log(resp);    
        });

邮递员输出

邮递员输出

浏览器网络请求/响应 在此处输入图片说明

返回this.http.post( http://127.0.0.1:8000/api/auth/login ).map((resp:Response)=> resp.json())

希望这会起作用

基本上,您将发送“字符串JSON”而不是JSON对象,直接发送Javascript对象而不是字符串将解决您的问题,

使用下面提到的方法将JSON数据发布到服务器,

var httpOptions = {
    headers: new HttpHeaders({
        'Accept':'application/json',
        'Content-Type': 'application/json'
    })
};

var dataToPost = {"email":"ab@gm.com","password":"12345678"}; 

this.http.post('http://127.0.0.1:8000/api/auth/login', dataToPost, httpOptions)
.subscribe(resp => {
    console.log(resp);    
});

这是由于CORB。

跨域读取阻止(CORB)是一种算法,可以在Web浏览器访问网页之前识别并阻止可疑的跨域资源负载。 CORB通过将敏感数据与跨源网页隔离开来,从而降低了泄露敏感数据的风险。

https://www.chromestatus.com/feature/5629709824032768

解决方案在禁用的网络安全模式下运行Chrome。 这对我有用https://stackoverflow.com/a/42086521/6687186

Win + R并粘贴

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM