Michal Bialek
Michal Bialek

Reputation: 499

HTTP POST request from Angular 2 client to Node.js server

I have a strange issue with sending POST request to my Node.js server. I have also some GET listeners but they work perfectly fine. So, I am trying to send a simple request from Angular 2 application (port 4200) to Node.js server (port 443) as followed but I receive an error:

XMLHttpRequest cannot load http://localhost:443/edit_comment. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Client service method:

   public saveComment(id: number, comment: string) : Observable<Response> {
        let data         = { id: id, comment: comment };
        let headers      = new Headers({'Content-Type': 'application/json'}); 
        let options      = new RequestOptions({ headers: headers });


        return this.http.post('http://localhost:443/edit_comment', JSON.stringify(data), options)
            .map((res:Response) => res.json())
            .catch((error:any) => Observable.throw(error.json().error || 'Server error')); 
    }

and node.js server side (with express library):

app.post('/edit_comment', (req, resp) => {
    console.log('blabla') //this log never displays
    resp.setHeader('Access-Control-Allow-Origin','*')
    resp.send(JSON.stringify('foo'))
});

The problem is that it seems that app.post callback function is not even called because console.log does not display 'blabla' message on screen.

Here you have also Request and Response headers from developer tools in my browser:

Request Headers:

Accept:*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:443
Origin:http://localhost:4200
Pragma:no-cache
Referer:http://localhost:4200/testlinemonitor
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36

Response Headers:

HTTP/1.1 200 OK
X-Powered-By: Express
Allow: POST
Content-Type: text/html; charset=utf-8
Content-Length: 4
ETag: W/"4-oCQ57CKdi+DnSwwWAjkjEA"
Date: Fri, 10 Mar 2017 12:49:41 GMT
Connection: keep-alive

Regards

Upvotes: 1

Views: 2415

Answers (2)

Łukasz
Łukasz

Reputation: 643

You backend is not able to respond for OPTIONS call. If you have cross origin requests, the browser always does preflight OPTIONS call. And then if successful, it does GET or POST. Please check network traffic in Chrome Debugger.

This is package for ExpressJS server https://github.com/expressjs/cors

Upvotes: 2

Matheus Martins
Matheus Martins

Reputation: 1042

You need to allow not only your allowed origins, but also allowed methods and headers.

Try adding this headers that allow CORS requests:

res.setHeader('Access-Control-Allow-Origin', '*')

//Add as many Headers as you want to line below
//If you use "Authentication" Header, insert it like 'Content-type, Authentication'
res.setHeader('Access-Control-Allow-Headers', 'Content-type')

res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')

Upvotes: 0

Related Questions