我正在尝试在具有Angular客户端的Node.js服务器的本地主机站点上启用CORS。
我不断得到:
CORS策略已阻止从源“ http://localhost:4200”访问“ localhost:3000 / api / v1 / users”处的XMLHttpRequest:仅协议方案支持跨源请求:http,数据,chrome, chrome-extension,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);
答案 0 :(得分:0)
要进行测试,您应该使用CORS浏览器插件。这样做的好处是,当您要为prod生成代码时,不必修改代码