vue-cli3+node项目跨域请求处理

跨域请求处理有两种方式,一种是在前端处理,一种是在后端处理,任选一种就可以了,但是建议前端处理,比较安全

第一种前端处理允许跨域

项目根目录新建一个文件vue.config.js,配置跨域

module.exports = {
    baseUrl: process.env.NODE_ENV === 'production' ? './' : '/',
    devServer: {
        port: 8081, // 端口号
        host: 'localhost',
        https: false, // https:{type:Boolean}
        open: true, //配置自动启动浏览器
        proxy: { // 配置跨域
            '/api': {
                target: 'http://localhost:8000/',
                ws: true,
                changOrigin: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        },
    }
}

第二种后端处理允许跨域

//设置跨域访问
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    next();
});

猜你喜欢

转载自blog.csdn.net/weixin_39675478/article/details/88884150