【问题标题】:Cors error in nestjs. it is not working withCredentialsNestjs 中的 Cors 错误。它不适用于凭据
【发布时间】:2021-12-30 19:06:24
【问题描述】:

API 中使用"{withCredentials:true}" 时出现以下错误。如果我不使用它,则它不起作用。

const submit = async(e:SyntheticEvent) =>{
    e.preventDefault();
    await axios.post('http://localhost:8000/api/login',{
        email,
        password
    });
}

以上工作正常。当我使用{withCredentials:true} 时,它会给出cors() 错误。

const submit = async(e:SyntheticEvent) =>{
    e.preventDefault();
    await axios.post('http://localhost:8000/api/login',{
        email,
        password
    },{withCredentials:true}); 
    setRedirect(true);

}

main.ts 文件中我有以下配置。

  const options = {
    origin: '*',
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    preflightContinue: false,
    credentials: true,
  };
  app.enableCors(options);

即使我尝试了credentials: false, 仍然无法正常工作。

我必须使用{withCredentials:true},以便我可以使用jwt tokens 进行授权。

【问题讨论】:

标签: node.js reactjs cors nestjs nestjs-config


【解决方案1】:

试试这个。

  const options = {
    origin: true,
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    preflightContinue: false,
    credentials: true,
    allowedHeaders: 'Content-Type, Accept',
  };
  app.enableCors(options);

【讨论】:

  • 永远不要这样做!您允许使用凭据的任意来源;它几乎使同源策略提供的保护无效。就安全性而言,这是一个糟糕的建议。
  • 当然...我以为是为了学习,所以我推荐
猜你喜欢
  • 1970-01-01
  • 2015-07-30
  • 2018-06-10
  • 2018-01-16
  • 2019-05-20
  • 1970-01-01
  • 2019-12-04
  • 2018-05-29
  • 2013-01-19
相关资源
最近更新 更多