即使使用 withCredential: true,axios 也无法通过请求发送 cookie [英] axios cannot send cookie with request even with withCredential: true

查看:87
本文介绍了即使使用 withCredential: true,axios 也无法通过请求发送 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这样的服务器上设置了

I already setup on server like this

    app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
  res.header(
    'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization,  X-PINGOTHER'
  );
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS');
  next();
});

和客户端的 axios (react) 像这样

and the axios on client side (react) like this

axios.defaults.withCredentials = true;
axios('http://127.0.0.1:3001/orders', {
  method: 'GET',
  withCredentials: true
}).then(res => {
     console.log(res);
   }).catch(err => {
     console.log(err.response);
   })

当我使用 Postman 进行测试并直接输入 chrome 时,一切正常.知道我的代码有什么问题吗?

Everything works fine when I test with Postman and type directly to chrome. Any idea what's wrong with my code?

推荐答案

如果你打算多次使用这个,那么只需创建一个 axios 配置:

If you plan on using this mulitple times, then just create an axios config:

client/src/utils/axiosConfig.js

import axios from 'axios';

const baseURL = process.env.NODE_ENV === "development"
  ? "http://localhost:3001/"
  : "http://example.com"

const app = axios.create({
    baseURL,
    withCredentials: true
})

/* 
  The below is required if you want your API to return 
  server message errors. Otherwise, you'll just get 
  generic status errors.

  If you use the interceptor below, then make sure you 
  return an "err" (or whatever you decide to name it) message 
  from your express route: 
  
  res.status(404).json({ err: "You are not authorized to do that." })

*/
app.interceptors.response.use(
  response => (response), 
  error => (Promise.reject(error.response.data.err))
)

export default app;

client/src/actions/exampleAction.js

import app from '../utils/axiosConfig';

export const exampleAction = () => (
  app.get('orders') // this will be defined as baseURL + "orders" (http://localhost:3001/orders)
    .then(res => console.log(res))
    .catch(err => console.log(err))
)

然后对于您的 API,您可以简单地使用 cors 而不是指定 CORS 标头.重新定义你的 express 中间件:

Then for your API, instead of specifying CORS headers, you can simply use cors wherever you're defining your express middleware:

const cors = require('cors');
const origin = process.env.NODE_ENV === "development" 
  ? "http://localhost:3000" 
  : "http://example.com"

app.use(
  cors({
    credentials: true,
    origin
  }),
);

这篇关于即使使用 withCredential: true,axios 也无法通过请求发送 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆