简体   繁体   中英

Angular HTTP post not accepting JSON response?

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 在此处输入图片说明

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

hopefully this will work

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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