Angular HTTP post not accepting JSON response?

自古美人都是妖i 提交于 2021-01-29 13:26:24

问题


I created an API in laravel and tested in postman and it is working perfect. But when I try it from angular it works fine for returning a string text but not for JSON response

I searched it on internet and found setting content-type:application/json and tried with different ways for setting content type in header but issue still persist

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

Postman Output

browser network request/response


回答1:


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

hopefully this will work




回答2:


Basically, you are sending "string JSON" instead JSON Object, send Javascript Object directly instead of string will solve your issue,

Use the below-mentioned way to post JSON data to the server,

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



回答3:


It was due to 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

Solution run chrome in disabled web security mode. This worked for me https://stackoverflow.com/a/42086521/6687186

Win+R and paste

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


来源:https://stackoverflow.com/questions/57973136/angular-http-post-not-accepting-json-response

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!