美文网首页
Angular 跨域的问题

Angular 跨域的问题

作者: 晨曦Bai | 来源:发表于2020-04-23 21:23 被阅读0次

Question:

Angular POST request been blocked by CORS policy: Response to preflight request doesn't pass access control check

需要先启动前端服务,然后在启动后台服务,才能顺利转发

https://www.jianshu.com/p/4982acbabb57

Answer:

1.  在前端解决跨域 
https://angular.cn/guide/build#proxying-to-a-backend-server

proxy.conf.json

{
    "/api": {
      "target": "http://localhost:3000",
      "secure": false,
      "pathRewrite": {
        "^/api": ""
      }
    }
  }
 this.http.get("/api").subscribe((res:any)=>{
      console.log('数据的返回',res)
    })    //该地址就是需要被代理的

2.  后端解决跨域

app.js

app.use((req, res, next) => {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
        next();

});


相关文章

网友评论

      本文标题:Angular 跨域的问题

      本文链接:https://www.haomeiwen.com/subject/wlbaihtx.html