简体   繁体   English

从Angular 2客户端到Node.js服务器的HTTP POST请求

[英]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. 将POST请求发送到我的Node.js服务器时遇到一个奇怪的问题。 I have also some GET listeners but they work perfectly fine. 我也有一些GET侦听器,但它们工作得很好。 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: 所以,我试图按照以下方式从Angular 2应用程序(端口4200)向Node.js服务器(端口443)发送一个简单请求,但我收到一个错误:

XMLHttpRequest cannot load http://localhost:443/edit_comment . XMLHttpRequest无法加载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. 对预检请求的响应未通过访问控制检查:请求的资源上不存在“ Access-Control-Allow-Origin”标头。 Origin ' http://localhost:4200 ' is therefore not allowed access. 因此,不允许访问源' http:// localhost:4200 '。

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): node.js服务器端(带有快速库):

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. 问题在于,由于console.log在屏幕上不显示“ blabla”消息,因此似乎没有调用app.post回调函数。

Here you have also Request and Response headers from developer tools in my browser: 在这里,您还可以从浏览器中的开发人员工具获得Request和Response标头:

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 问候

You backend is not able to respond for OPTIONS call. 您的后端无法响应OPTIONS调用。 If you have cross origin requests, the browser always does preflight OPTIONS call. 如果您有跨源请求,则浏览器将始终执行预检OPTIONS调用。 And then if successful, it does GET or POST. 然后,如果成功,它将执行GET或POST。 Please check network traffic in Chrome Debugger. 请在Chrome调试器中检查网络流量。

This is package for ExpressJS server https://github.com/expressjs/cors 这是ExpressJS服务器的软件包https://github.com/expressjs/cors

You need to allow not only your allowed origins, but also allowed methods and headers. 您不仅需要允许允许的来源,还需要允许的方法和标头。

Try adding this headers that allow CORS requests: 尝试添加以下允许CORS请求的标头:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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