【发布时间】: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。
我试过了:
- app.use(cors())
- app.use 函数来自这里:https://enable-cors.org/server_expressjs.html
- 来自here 的特定app.use 函数,origin='localhost:4200'
- origin='*' 的 app.use 函数
我当前的节点 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<string[]>('http://localhost:3000/'+'api/v1/users').subscribe(x=>this.data=x)(包括http://协议部分)而不仅仅是this.http.get<string[]>('localhost:3000/'+'api/v1/users').subscribe(x=>this.data=x) -
@Sudhakar 该解决方案对我有用。想把它写下来并作为答案提出来吗?
标签: javascript node.js angular cors