Vuecli3+express实现跨域

在根目录(和package.json同级)下创建vue.config.js,内容如下

module.exports = {
    devServer: {
        port: 8080,
        host: 'localhost',
        proxy: {
            '/api': {
            target: 'http://localhost:3000', //服务器接口
            changeOrigin: true,
            pathRewrite: {
                '^/api': ''
                }
            }
        }
    }
  }

main.js中引入axios

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

import Axios from "axios"
Axios.defaults.baseURL = "http://localhost:3000"   
Vue.prototype.$axios = Axios

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

Home.vue



express服务器部分

routes/test.js

var express=require('express')
var router=express.Router()

router.get('/',function(req,res,next){
    var data={
        code:0,
        data:{name:'user',pwd:123},
        isSuccess:true,
        msg:'请求成功'
    };
    res.json(data);
})

module.exports=router

app.js中引入test.js

var testRouter = require('./routes/test')
app.use('/test',testRouter);

在app.js中添加如下代码:(这里很关键)

需要先安装cors:  cnpm i cors -S

//跨域问题解决方案
const cors = require('cors');  
app.use(cors({  
    origin:['http://localhost:8080'],
    methods:['GET','POST'],
}));
//跨域问题解决方案
app.all('*',function (req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
 next(); 
});

 

运行vue项目

Vuecli3+express实现跨域_第1张图片

参考:https://blog.csdn.net/weixin_41018304/article/details/102532085 

你可能感兴趣的:(Vue,Vuecli3)