【问题标题】:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost3000跨域请求被阻止:同源策略不允许在 http://localhost3000 读取远程资源
【发布时间】:2021-12-18 16:10:23
【问题描述】:

proxy.conf.json 来自 angular,并且还在“serve”中的 angular.json 中配置了该文件:

{
    "/front-v1": {
        "target": "http://localhost:3000",
        "secure": false,
        "logLevel": "debug"
    }
}

我的服务文件:

async getData() {
    return this.http.get(this.getDataUrl,
      {headers: {
        'Access-Control-Allow-Origin': this.getDataUrl,
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
        'Access-Control-Allow-Credentials': ''
      }, responseType: 'json'} ).pipe((result) => {
      return result;
    });
  }

来自nestjs的main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // app.enableCors();
  app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    next();
  });
  app.enableCors({
    allowedHeaders:"*",
    origin: "*",
});
  await app.listen(3000);
}
bootstrap();

这是我的错误: 跨域请求被阻止:同源策略不允许读取位于 http://localhost3000/india 的远程资源。 (原因:CORS 请求未成功)。

解决方案

问题出在我在客户端的代理中。正确制作proxy.config。

【问题讨论】:

  • 您真的想从您的客户端代码中删除所有这些 cors 标头。它不起作用,实际上可能导致 Cors 问题..

标签: angular ubuntu firefox cors nestjs


【解决方案1】:

您可以在应用初始化时指定cors: truecors: true 将设置默认的 cors 配置,即允许所有来源。或者您可以指定自己的配置。

const app = await NestFactory.create(AppModule, {
    cors: true,
});

【讨论】:

  • 我试过但没用..
  • 我在ubuntu上运行.. ubuntu有什么问题吗,谢谢。
  • 您的操作系统应该没有问题。您是否尝试过删除其他代码并仅保留const app = await NestFactory.create(AppModule, { cors: true });
猜你喜欢
  • 2016-12-04
  • 2021-04-04
  • 2014-10-17
  • 2015-07-22
  • 2018-04-20
  • 2014-07-20
相关资源
最近更新 更多