Angular2应用程序调用node.js函数 [英] Angular2 application call node.js function
问题描述
好,所以我有一个在http://localhost:4200/
上运行的Angular2
应用程序,在此应用程序内,我试图调用一个位于当前在http://localhost:3000/
上运行的单独node.js
应用程序中的函数
Ok so I have an Angular2
application running on http://localhost:4200/
, Inside this app I'm trying to call a function located in a seperate node.js
application currently running on http://localhost:3000/
我从Angular2
应用程序拨打的电话:
My call from the Angular2
application:
deletePhoto(photoId: string) {
var options = new RequestOptions({
headers: new Headers({
'Accept': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:4200'
})
});
let url = `http://localhost:3000/delete?photoId=${photoId}`;
this.http.post(url, options).subscribe(response => {
let user = response.json()
console.log(user);
},
err => {
console.log('Unable to call delete photo', err);
});
}
这是我的node.js
函数:
var express = require('express')
var app = express();
app.post('/delete', function (req, res) {
req.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', '*');
var photoId = req.query['photoId'];
//var userId = req.query['userId'];
res.json({ "photoId": photoId, "test": "Testing node server" })
})
但是我在浏览器中收到的错误是:
However the error I receive in the browser is:
对预检请求的响应未通过访问控制检查:所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问' http://localhost:4200 '.
现在,在搜索了此错误之后,我读到我需要在请求的资源上设置标头,因此我在node
方法上添加了req.setHeader
,但仍然无济于事,我也确实在Angular2
中进行了设置应用程序以查看其含义,但可悲的是结果相同.
Now after googling this error, I read I needed to set the header on the requested resource so I added the req.setHeader
on my node
method but still with no avail, I did also set it within my Angular2
app to see if that's what it meant but sadly same result.
我已经阅读过cors
,但不幸的是,我仍然对此感到困惑.
I have read up on cors
but unfortunately I'm still confused by it.
推荐答案
You must also add code to handle the OPTIONS request that browsers send for CORS preflights:
app.options('/delete', function(req, res) {
res.send(200);
});
这种添加只会导致您的Node应用发送带有所有必需的Access-Control-*
响应标头的无正文的200
响应.
That addition just causes your Node app send a 200
response with no body with all the necessary Access-Control-*
response headers.
这篇关于Angular2应用程序调用node.js函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!