【问题标题】:No Cookies in Headers using Axios withCredentials: true使用 Axios withCredentials 的标头中没有 Cookie:true
【发布时间】:2021-06-15 16:10:32
【问题描述】:

我正在使用带有 jwt 身份验证的 ReactJS 和 ExpressJS。在我的服务器中,我有这样的 cors 配置

const corsOptions = {
  //To allow requests from client
  origin: true,
  credentials: true,
  methods: ['GET', 'PUT', 'POST', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization', 'Set-Cookie'],
};

在我的客户端中,我像这样向服务器发送请求

export function createNewRequest(data, callback) {
 axios.post(`${process.env.REACT_APP_API}/api/requests`, data,
     {
         withCredentials: true
     }).then(res => {
         callback(res.data);
     })
     .catch(err => {
        if (err.response) {
            if (err.response.status === 403 || err.response.status === 401) {
                getToken(createNewRequest(data, callback));
            } else {
                callback(err.response.data);
            }
        }
     })
}

在我的本地环境中,我进行了测试,一切都运行良好。但是当我部署我的服务器时,我尝试从本地客户端向服务器发送请求。服务器不会在标头中接收 cookie。
我试过像这样设置原点

const corsOptions = {
 //To allow requests from client
 origin: ['http://localhost:3000'],
 credentials: true,
 methods: ['GET', 'PUT', 'POST', 'DELETE'],
 allowedHeaders: ['Content-Type', 'Authorization', 'Set-Cookie'],
};

并尝试使用凭据设置默认值

axios.defaults.withCredentials = true;

但这些都不起作用。谁能向我解释我做错了什么并帮助我解决这个问题

【问题讨论】:

    标签: reactjs express cookies axios cross-domain


    【解决方案1】:

    尝试在没有选项的情况下允许app.use(cors()); 像这样(允许一切)。 代码示例:

    app.use(cors());
    
    app.use(bodyParser.json({ origin: "https://famegoal.com/" }));
    
    app.use("/function", couponRoutes);
    
    mongoose
      .connect(
        `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.qvs4c.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`
      )
      .then(() => {
        app.set("port", process.env.PORT || 5000);
    
        app.listen(app.get("port"), function () {
          console.log("Node app is running on port", app.get("port"));
        });
      })
      .catch((err) => {
        console.log(err);
      });

    这并不安全,但它是一个很好的解决方案。

    【讨论】:

    • 我先尝试了这个,由于 CORS 策略,请求被阻止,所以我需要指定 corsOptions
    【解决方案2】:

    在你的 app.js 中设置如下中间件

    app.use(function(req, res, next) {
      res.header('Content-Type', 'application/json;charset=UTF-8')
      res.header('Access-Control-Allow-Credentials', true)
      res.header(
        'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, 
      Accept'
      )
      next()
    });
    

    在 reactjs 中使用 withCredentials: true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 2022-01-16
      • 2018-10-19
      • 1970-01-01
      • 2014-08-17
      • 2018-07-28
      • 1970-01-01
      相关资源
      最近更新 更多