vue学习日记:vue跨域处理

vue跨域的方法一种是直接在config文件夹下的index.js中的dev对象中配置proxyTable属性,

另一种是新建一个proxyConfig.js文件,然后注入index.js中,本质其实是一样的。

只是后一种将配置单独写成了一个文件而已。这里我选择了第二种写法。

首先在config文件夹下新建一个proxyConfig.js文件,代码如下:

module.exports = {
    proxy: {
        '/jwt': {    //将http://192.168.**.***:9000印射为/jwt
            target: 'http://192.168.**.***:9000',  // 接口域名
            secure: false,  // 如果是https接口,需要配置这个参数
            changeOrigin: true,  //是否跨域
            // pathRewrite: {
            //     '^/jwt': ''   //需要rewrite的,
            // }
        }
    }
}

这个就代表所有以jwt开头的请求,将发往http://192.168.**.***:9000,

如果pathRewrite那个部分不注释掉的话,就代表所有以jwt开头的请求,

将发往http://192.168.**.***:9000,并且在请求的时候删掉请求地址中的/jwt

然后是index.js中的写法:

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path');
const proxyConfig = require("./proxyConfig");

module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: proxyConfig.proxy,

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 9090, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

就是很简单的引入并配置就好了。接下来就可以测试跨域是否成功了。

原文地址:https://www.cnblogs.com/xianxiaobo/p/9359897.html