您的位置:首页 > Web前端 > Node.js

详解Vue 开发模式下使用nodejs解决跨域问题

2017-08-16 00:00 1281 查看
摘要: Vue-cli 创建的项目如何跨域请求 ? Vue 开发模式下直接利用 Node.js 代理服务器,实现跨域请求

详解Vue 开发模式下直接利用 Node.js 代理服务器,实现跨域请求

本篇文章主要介绍了Vue 开发模式下跨域问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

使用nodejs做代理

1、鉴于vue使用脚手架vue-cli创建的项目,作者已经给提供好了解决的方法。

2、找到项目文件夹下的config/index.js, 里面有一行proxyTable: {}, 这里就是作者为我们留的接口, 我们添加代理规则进去

// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')

module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8093,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/account': {
target: 'http://10.143.47.26:8080',
changeOrigin: true,
},
'/services': {
target: 'http://10.143.47.26:8080',
changeOrigin: true,
},
'/api': {
target: 'http://www.xxx.com/api.php/',
changeOrigin: true,
pathRewrite: {
'^/api': '/'
}
},
},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}

这里target:为目标域名,pathRewrite为转换规则,请求数据时将接口地址 根据转换规则请求就可以解决跨域啦!(这里也可以配置headers,设置cookis,token等)

通过设置changeOrigin:true: 开启代理

pathRewrite: 意为重写路径

'^/api': '/': 由于'^/api'是虚拟目录实际上是不存在的,不去掉的话会变成'http://127.0.0.1:3000/api',所以得去掉 配置了上面的参数后,在调用时就要(这里用的是axios,例如地址是http://127.0.0.1:3000/aaa)

比如要请求的接口为http://192.168.400:3000/main/getUserInfo.action

axios.post('/api/main/getUserInfo.action', {})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

为什么要有个‘/api’?因为步骤1那里写的是‘/api’,那怎么办?别忘了,因为用的是axios,所以可以配置一下baseURL ,我这里就全局配置baseURL

在实际工作中,我们还需要做些其他的,比如在axios中配置baseUrl:

import axios from 'axios';

// 添加响应拦截器
axios.interceptors.request.use(function (config) {
// 配置发送请求的信息

return config;
}, function (error) {
return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
// 配置请求回来的信息

return response;
}, function (error) {
return Promise.reject(error);
});

var http = axios.create({
timeout: 8000, /*设置请求超时时间*/
baseURL:'http://192.168.400:3000',

});

//axios.defaults.baseURL = '/api'   //这个是别的重写全局配置baseURL

// Alter defaults after instance has been created
http.defaults.headers.common['Authorization'] = '';

export default http;

/**导出http,在mainjs中引用
import http from './config/axiosConfig';
Vue.prototype.$http = http;
**/

其中 '/api' 为匹配项,target 为被请求的地址 因为在 ajax 的 url 中加了前缀 '/api',而原本的接口是没有这个前缀的 所以需要通过 pathRewrite 来重写地址,将前缀 '/api' 转为 '/' 如果本身的接口地址就有 '/api' 这种通用前缀,就可以把 pathRewrite 删掉

参考地址:http://www.jianshu.com/p/88d41de7f4b5

http://www.jb51.net/article/115495.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息