从Angular 2客户端到Node.js服务器

时间:2017-03-10 12:55:09

标签: javascript angularjs node.js http post

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

  

XMLHttpRequest无法加载http://localhost:443/edit_comment。响应   预检请求没有通过访问控制检查:否   '访问控制允许来源'标题出现在请求的上   资源。起源' http://localhost:4200'因此是不允许的   访问。

客户服务方法:

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

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

问题是,似乎甚至没有调用app.post回调函数,因为console.log没有显示&#39; blabla&#39;屏幕上的消息。

您还可以在我的浏览器中找到开发人员工具的请求和响应标头:

请求标题:

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

响应标题:

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

此致

2 个答案:

答案 0 :(得分:2)

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

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

的包

答案 1 :(得分:0)

您不仅需要允许允许的来源,还需要允许方法和标题。

尝试添加允许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')