Angular HTTP post 不接受 JSON 响应?

Angular HTTP post not accepting JSON response?

我在 laravel 中创建了一个 API 并在 postman 中进行了测试,它运行良好。但是当我从 angular 尝试它时,它可以很好地返回字符串文本但不适用于 JSON 响应

我在互联网上搜索并找到设置 content-type:application/json 并尝试使用不同的方法在 header 中设置内容类型,但问题仍然存在

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

邮差输出

浏览器网络request/response

return this.http.post(http://127.0.0.1:8000/api/auth/login, obj,HTTPOptions ).map((resp: Response) => resp.json())

希望这会奏效

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

使用下面的方式postJSON数据到服务器,

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。

Cross-Origin Read Blocking (CORB) is an algorithm that can identify and block dubious cross-origin resource loads in web browsers before they reach the web page. CORB reduces the risk of leaking sensitive data by keeping it further from cross-origin web pages.

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

解决方案运行 chrome 禁用网络安全模式。 这对我有用

Win+R 并粘贴

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