0

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

Postman-output

browser network request/response enter image description here

imabdullah
  • 327
  • 1
  • 5
  • 24

3 Answers3

0

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

hopefully this will work

0

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);    
});
Arsal Imam
  • 2,882
  • 2
  • 24
  • 35
0

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 
imabdullah
  • 327
  • 1
  • 5
  • 24
  • But if I able to work when development, in production it will behave the same isnt it? Or is it (CORS) only occur in development?? – Sandeep Thomas Apr 21 '20 at 15:36