arlyxiao / best-practice

1 stars 0 forks source link

nestjs/axios 跨域踩坑 #87

Open arlyxiao opened 2 years ago

arlyxiao commented 2 years ago

先贴代码 服务端 nestjs -> main.js

app.enableCors({
    allowedHeaders: ['content-type'],
    origin: (origin, callback) => {
      if (!origin) {
        callback(null, true);
        return;
      }

      if (origin.includes('localhost')) {
        callback(null, true)
      } else {
        callback(new Error('Not allowed by CORS'))
      }
    },
    credentials: true,
  });

controller, set cookie

response.cookie('token', 'your-token-here', {
  expires: new Date(Date.now() + 360000000),
  httpOnly: false,
  sameSite: 'none',
  secure: true,
  domain: 'your-domain' // here is important to note
});

客户端

const instance = Axios.create({
  baseURL: 'your-base-url',
  withCredentials: true,
  headers: {
    "Content-Type": "application/json",
  }
})