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

时间:2021-02-28 16:59:07

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:

将POST请求发送到Node.js服务器时遇到一个奇怪的问题。我也有一些GET听众,但他们的工作非常好。所以,我试图从Angular 2应用程序(端口4200)发送一个简单的请求到Node.js服务器(端口443),但我收到一个错误:

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.

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

问题是似乎甚至没有调用app.post回调函数,因为console.log不会在屏幕上显示“blabla”消息。

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

2 个解决方案

#1


2  

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.

您的后端无法响应OPTIONS调用。如果您有跨源请求,则浏览器始终执行预检OPTIONS调用。然后如果成功,它会进行GET或POST。请检查Chrome调试器中的网络流量。

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

这是ExpressJS服务器https://github.com/expressjs/cors的包

#2


0  

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

#1


2  

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.

您的后端无法响应OPTIONS调用。如果您有跨源请求,则浏览器始终执行预检OPTIONS调用。然后如果成功,它会进行GET或POST。请检查Chrome调试器中的网络流量。

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

这是ExpressJS服务器https://github.com/expressjs/cors的包

#2


0  

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