send corss-domain request with cookie(login state)

client side


made a request.js file what the 'withCredentials: true,' is most important thing to do. It allows browser to catch cookie with corss-domain request.


import axios from 'axios'

const service = axios.create({
  baseURL: 'http://localhost:3000', // process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

export default service

then you can make a real request in you file.

import request from '@/request'

export function events() {
  return request({
    url: '/api/event',
    method: 'get'
  })
}

server side


first of all you need install cors

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors({
  credentials: true,
  origin: ['http://localhost:3001'],//client side server address/must be
}));

CAUTION

origin: ['http://localhost:3001']
can not be
origin: '*'
the * will conflict with credentials : true
you have to assign it to your client side address

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容