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

<template>
  <div class="home">
    <button @click="send()">click</button>
  </div>
</template>
<script>
export default {
  methods:{
    send(){
      this.$axios.get('/test')
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });
    }
  }
}
</script>

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项目

扫描二维码关注公众号,回复: 9203770 查看本文章

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

发布了319 篇原创文章 · 获赞 124 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/qq_40323256/article/details/103077241
今日推荐