Node.js 从本地角度项目CORS ERR向本地节点服务器发出Http请求
我正在制作一个本地项目,我使用angular 6表单运行在节点服务器上localhost:4200/和节点服务器上但在不同端口运行的NodeJlocalhost:2000 问题是,即使我准备好了节点来接受请求,也会出现CORS安全错误 角度代码Node.js 从本地角度项目CORS ERR向本地节点服务器发出Http请求,node.js,angular,http,cors,Node.js,Angular,Http,Cors,我正在制作一个本地项目,我使用angular 6表单运行在节点服务器上localhost:4200/和节点服务器上但在不同端口运行的NodeJlocalhost:2000 问题是,即使我准备好了节点来接受请求,也会出现CORS安全错误 角度代码 register(regData){ return this.httpClient.post(this.url,regData); } npm安装cors——保存//intsall cors(NodeJs) NodeJs const e
register(regData){
return this.httpClient.post(this.url,regData);
}
npm安装cors——保存//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
源“”已被CORS策略阻止:交叉
只有协议方案支持原始请求:http、数据、,
chrome,chrome扩展,https
此错误消息表示用于客户端请求的URL包含不正确的协议。在您的例子中,URL中根本没有协议 因此,您的问题的解决方案是使用
http://localhost:2000
而不是localhost:2000
协议是URL的重要组成部分,因为协议之间有很大的差异。例如,您的URL可能看起来像
file:///localhost...
或ftp://localhost...
等等。因此,最好总是直接定义它。您是否尝试将url更改为http://localhost:2000
(而不是localhost:2000
)在客户端代码中?确保this.url
(在this.httpClient.post(this.url,regData);
)以http://...
@MaxMartynov谢谢,这解决了我的问题