【问题标题】:Cross origin requests are only supported for protocol schemes. Node.js server Angular front end [duplicate]仅协议方案支持跨源请求。 Node.js服务器Angular前端[重复]
【发布时间】:2019-08-26 23:27:48
【问题描述】:

我正在尝试在 localhost 站点上为带有 Angular 客户端的 Node.js 服务器启用 CORS。

我不断得到:

从源“http://localhost:4200”访问“localhost:3000/api/v1/users”处的 XMLHttpRequest 已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome-扩展名,https。

我试过了:

我当前的节点 server.js 文件:

const express = require('express')
const app = express()
const cors = require('cors');

const port = 3000

///////
app.use(cors());

app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});

///////
app.get('/*', (request, response) => {
  response.send('Hello from Express!')
})

app.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log(`server is listening on ${port}`)
})

调用节点路由的我的 Angular 方法(我知道这是有效的,因为我在上面显示的 chrome 控制台中收到了 cors 错误):

this.http.get<string[]>('localhost:3000/'+'api/v1/users').subscribe(x=>this.data=x);

【问题讨论】:

  • 使用this.http.get&lt;string[]&gt;('http://localhost:3000/'+'api/v1/users').subscribe(x=&gt;this.data=x)(包括http://协议部分)而不仅仅是this.http.get&lt;string[]&gt;('localhost:3000/'+'api/v1/users').subscribe(x=&gt;this.data=x)
  • @Sudhakar 该解决方案对我有用。想把它写下来并作为答案提出来吗?

标签: javascript node.js angular cors


【解决方案1】:

为了进行测试,您应该使用 CORS 浏览器插件。这样做的好处是,当你想为 prod 构建代码时,你不必修改代码

【讨论】:

    猜你喜欢
    • 2018-06-29
    • 2017-09-29
    • 1970-01-01
    • 2018-10-03
    • 2016-07-19
    • 1970-01-01
    • 2017-02-22
    • 2017-10-11
    相关资源
    最近更新 更多