vue开发环境解决跨域的几种方法

解决方案

解决跨域的方法很多 后端有设置请求   前端有jquery的jsonp、script的请求转发等,出现跨域问题主要时因为浏览器的同源策略,所以只要在中间做个代理请求,就可以巧妙的避开跨域问题

一,使用proxyTable属性

  这里vue脚手架生成的标准项目为准。一般在项目config目录下面有个index文件。里面格式如下:

'use strict'
const path = require('path')
module.exports = {
    dev: {
        // Paths
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: {
            '/api': {
                target: 'http://localhost:7001',//后端接口地址
                changeOrigin: true,//是否允许跨越
                pathRewrite: {
                    '^/api': '/api',//重写,
                }
            }
        },
        host: '192.168.0.104',
        port: 8081,
        autoOpenBrowser: false,
        errorOverlay: true,
        notifyOnErrors: true,
        poll: false,
        useEslint: true,
        showEslintErrorsInOverlay: false,
        devtool: 'eval-source-map',
        cacheBusting: true,
        cssSourceMap: false,
    },

}

二,通过ngnix中的proxy代理实现请求的转发

enter image description here

三、使用webpack的插件后端程序代理

  当然上面2个方法都需要后端的配合和需要修改服务器配置。所有还有一种方法不需要他们配合 ,我们自己就可以做到。就是我们自己启一个后端程序做代理。然后把所有的请求转发到服务器。这里要用到node的一个包http-proxy-middleware。关键代码(express)如下

var express = require('express');
var proxy = require('http-proxy-middleware');


var proxyTable = config.dev.proxyTable;



var app = express();

app.use('/api', proxy({target: 'http://www.example.org', changeOrigin: true}



Object.keys(proxyTable).forEach(function (context) {
  var options = proxyTable[context]
  if (typeof options === 'string') {
    options = { target: options }
  }
  app.use(proxyMiddleware(context, options))
})

猜你喜欢

转载自blog.csdn.net/margin_0px/article/details/81315479