带有反应前端的nestjs中的Cors策略错误

问题描述 投票:0回答:1

我在使用 React 前端配置 Nest Cors 策略时出错

错误图片

我已经使用了默认的nest js cors配置,如下所示 这是我的巢代码

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import helmet from 'helmet';
import * as cookieParser from 'cookie-parser';
import { NextFunction, Request, Response } from 'express';
async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  app.use(function (request: Request, response: Response, next: NextFunction) {
    response.setHeader('Access-Control-Allow-Origin', process.env.FRONT_URL);
    next();
  });
  app.enableCors({
    origin: process.env.FRONT_URL,
    credentials: true,
  });

  app.setGlobalPrefix('api');
  app.use(helmet());
  app.use(cookieParser());
  await app.listen(process.env.HOST || 3001);
}
bootstrap();

我在前端使用 axios,我这样配置 这是我的反应代码

import axios, { AxiosInstance } from "axios";
import { getCookie } from "./cookie.config";
import { ENUMs } from "../enum";

export const api: AxiosInstance = axios.create({
  baseURL: "/api",
  headers: {
    "Content-Type": "application/json",
  },
});

export const authApi: AxiosInstance = axios.create({
  baseURL: "/api",
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${getCookie({ name: ENUMs.COOKIE_NAME })}`,
    common: {
      Authorization: `Bearer ${getCookie({ name: ENUMs.COOKIE_NAME })}`,
    },
  },
  withCredentials: true,
});


我想解决这个cors问题,我在github上尝试了很多解决方案,但没有成功

reactjs cors nestjs nest
1个回答
0
投票

发生错误是因为配置中的

origin
正在接收字符串并且应该接收函数。

我如何在工作项目中使用它的基本示例。

import { HttpException, HttpStatus } from '@nestjs/common';

app.enableCors({
    exposedHeaders: ['X-Total-Count'],
    origin: function (origin, callback) {
        const frontUrls = process.env.FRONT_URL.split(',').map((url) => url.trim());

        if (frontUrls.indexOf(origin) !== -1) {
          callback(null, true);
        } else {
          callback(
            new HttpException('Not allowed by CORS', HttpStatus.UNAUTHORIZED),
          );
        }
    },
});

如果你的环境变量

FRONT_URL
只有一个URL,你可以按照下面的方式使用它,它应该可以工作。

import { HttpException, HttpStatus } from '@nestjs/common';


app.enableCors({
    exposedHeaders: ['X-Total-Count'],
    origin: function (origin, callback) {
        if (process.env.FRONT_URL === origin) {
            callback(null, true);
        } else {
            callback(
                new HttpException('Not allowed by CORS', HttpStatus.UNAUTHORIZED),
            );
        }
    },
});
© www.soinside.com 2019 - 2024. All rights reserved.