Vue + Node 项目中的跨域请求

需要:Vue-cli 2.x 版本和 Vue-cli 3.0

修改vue.config.js

module.exports = {
    // 配置跨域代理
    devServer: {
        proxy: {
            '/api': {
                target: 'http://localhost:8081',    // 你自己的api接口地址
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                    '^/api': '/api/',  
                }
            }
        }
    }
};

上面的代码等同于一下代码:

module.exports = {
    // 配置跨域代理
    devServer: {
        proxy: {
            '/api': {
                target: 'http://localhost:8081/api',    // 你自己的api接口地址
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                    '^/api': '',  
                }
            }
        }
    }
};

调用

import axios from 'axios';
export default {
    data() {
        return {}
    },
    created() {
        axios({
            method: 'get',
            url: "/api/goods"    
        }).then(data => {
            console.log(data);
        });
    }
};

后端设置

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

// api 返回的结果
const goods = {
    name: "goods",
    weight: 200
};

// 设置跨域
app.all("*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); //设置允许跨域的域名,*代表允许任意域名跨域
    res.header("Access-Control-Allow-Headers", "content-type"); //允许的header类型
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS"); //跨域允许的请求方式
    if (req.method.toLowerCase() == 'options')
        res.send(200); //让options尝试请求快速结束
    else
        next();
});

app.get('/api/goods', (req, res) => {
    res.json({
        errno: 200,
        data: goods
    });
});


var server = app.listen(8081, () => {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Server is running at: http://%s:%s', host, port);
})


再次调用

import axios from 'axios';
export default {
    data() {
        return {}
    },
    created() {
        axios({
            method: 'get',
            url: "http://localhost:8081/api/goods"
        }).then(data => {
            console.log(data);
        });
    }
};

评论