解决 eggjs missing csrf token 错误

2,983 阅读1分钟

axios

import Cookies from 'js-cookie'

/* eggjs 默认值,可修改 */
const xsrfCookieName = 'csrfToken';
const xsrfHeaderName = 'x-csrf-token';

const http = axios.create({
  /.../
  withCredentials: true,
  xsrfCookieName,
  xsrfHeaderName,
});

http.interceptors.request.use(
  (config) => {
    /* header 中添加 csrfToken */
    config.headers[xsrfHeaderName] = Cookies.get(xsrfCookieName);
    return config;
  },
  (error) => Promise.reject(error),
);

eggjs

/* 添加 egg-cors */

/* /config/plugin.ts */
const plugin: EggPlugin = {
  /.../
  cors: {
    enable: true,
    package: 'egg-cors',
  },
};

/* /config/config.default.ts */
const bizConfig = {
  /* ... */
  cors: {
    origin: 'http://localhost:8080',
    credentials: true,
  },
};