【问题标题】:Cross-Origin Request Blocked on requests between 2 local apps跨域请求被 2 个本地应用程序之间的请求阻止
【发布时间】:2020-05-22 18:15:23
【问题描述】:

我正在构建 Angular 8 应用程序(使用 localhost:4200),这个应用程序应该使用不同的端点(如 localhost:5000/contacts)从另一个应用程序(NodeJS 应用程序,使用 localhost:5000)获取和发布一些 JSON 数据.当我打电话给 localhost:5000/contacts 时——我收到一个错误 我试图做以下事情来解决这个错误: 1)我在我的数据源应用程序的响应中添加了标题: router.get("/contacts", async (req: Request, res: Response) => { const contactsGetResponse = accountingApi.getContacts(req.session.activeTenant.tenantId); res.header('Access-Control-Allow-Origin', 'http://localhost:4200'); res.header('Access-Control-Allow-Methods', 'GET,PUT,OPTIONS'); res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, \n' + 'Origin, Authorization, Accept, Client-Security-Token, Accept-\n' + 'Encoding, X-Auth-Token, content-type'); } 2)在调用api的函数中添加头文件:

public getContacts(){
  public corsHeaders = new HttpHeaders({
  'Content-Type': 'application/json;charset=utf-8',
  'Accept': 'application/json',
  'Access-Control-Allow-Origin': 'http://localhost:5000/'
});
let httpOptions;
  httpOptions = {
    headers: this.corsHeaders
  };

  const url = environment.myEndpoint + '/contacts';
  return this.httpClient.get(environment.myEndpoint + '/contacts', httpOptions);

} 但我仍然得到这个错误。 我知道这里已经有很多类似的问题。但没有什么对我有用。有人可以帮我吗?

【问题讨论】:

    标签: node.js angular http-headers


    【解决方案1】:

    npm i cors 然后 在后端使用app.use(cors()),假设您使用的是expressjsapp=express() 代码应该是这样的

    const app = express()
    const cors=require('cors')
    app.use(cors())
    app.get('/',(req,res)=>{
       res.send()
    })
    
    

    【讨论】:

    • 我应该为这两个应用安装 cors 吗?还是只为其中之一?
    • 对于节点,仅后端
    • 这个解决方案似乎对我有用 - 我安装了 cors lib,将 Access-Control-Allow-Origin 标头放入响应中。它似乎正在工作。将继续测试。
    猜你喜欢
    • 2021-08-30
    • 2019-11-04
    • 2017-02-06
    • 2015-06-22
    • 2021-06-26
    • 2014-10-13
    • 2018-09-17
    相关资源
    最近更新 更多