【发布时间】:2019-06-13 10:52:55
【问题描述】:
我正在做一个本地项目,我使用在节点服务器 localhost:4200/ 上运行的 angular 6 形式和在节点服务器上运行但在不同端口 localhost:2000 上的 nodeJs强>
即使我准备好 nodejs 来接受请求,问题还是出现 CORS 安全错误。
角度代码
register(regData){
return this.httpClient.post(this.url,regData);
}
npm install cors --save // intsall cors (NodeJs)
NodeJs
const express = require('express')
,cors = require('cors')
,app = express();
var bodyParser = require('body-parser');
const productR = require('./routes/product');
// middleware
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
var originsWhitelist = [
'http://localhost:4200', //this is my front-end url for development
'http://127.0.0.1:4200'
];
var corsOptions = {
origin: function(origin, callback){
var isWhitelisted = originsWhitelist.indexOf(origin) !== -1;
callback(null, isWhitelisted);
},
credentials:true
}
app.use(cors(corsOptions));
app.use('/products', productR);
错误信息
从 'localhost:2000/products/create' 访问 XMLHttpRequest 来源“http://localhost:4200”已被 CORS 策略阻止:交叉 源请求仅支持协议方案:http、data、 铬,铬扩展,https。
【问题讨论】:
-
您是否尝试在客户端代码中将 url 更改为
http://localhost:2000(而不是localhost:2000)?确保this.url(在this.httpClient.post(this.url,regData);)以http://...开头 -
@MaxMartynov 谢谢,这解决了我的问题