【问题标题】:Http Request to a local node server from local angular project CORS ERR从本地角度项目 CORS ERR 到本地节点服务器的 Http 请求
【发布时间】: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 谢谢,这解决了我的问题

标签: node.js angular http cors


【解决方案1】:

此错误消息表示您用于客户端请求的 URL 包含不正确的协议。在您的情况下,URL 中根本没有协议。

因此,您的问题的解决方案是使用http://localhost:2000 而不是localhost:2000

协议是 URL 的重要组成部分,因为协议之间存在很大差异。例如,您的 URL 可能看起来像 file:///localhost...ftp://localhost... 等等。所以还是直接定义比较好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    相关资源
    最近更新 更多