vue项目中,前端与后台进行数据请求或者提交的时候,如果后台没有设置跨域,前端本地调试代码的时候就会报“No ‘Access-Control-Allow-Origin’ header is present on the requested resource.” 这种跨域错误。
搜素资料,发现方式五花八门,什么修改config/index.js中的配置,但是我的项目里面根本就没有这文件夹,大多都是过时资料。
本文主要介绍如何使用反向代理进行跨域。
vue-cli3.0致力于Vue生态中的工具基础标准化。它确保了各种构建工具能够基于智能的默认配置即可平稳衔接,这样你就可以专注在撰写应用上,减少配置的时间。查看如下文件,会发现相比于vue-cli2.0少了build与config文件夹,所以vue-cli3提供了一个可选的配置文件 ——vue.config.js。请具体参考4和5(打包配置),这里只详细解读文件作用。
Vue.config.js是一个可选的配置文件,如果项目的根目录存在这个文件,那么它就会被 @vue/cli-service 自动加载。你也可以使用package.json中的vue字段,但要注意严格遵守JSON的格式来写。这里使用配置vue.config.js的方式进行处理。
在module.exports = {}添加如下代码:
devServer: { proxy: { '/api': { target: 'http://dev.admin.carrots.ptteng.com', ws: true, changeOrigin: true, pathRewrite: { '^/api': 'http://dev.admin.carrots.ptteng.com' }, }, } }, // devServer:{ // proxyTable: { // '/api': { //使用"/api"来代替"http://f.apiplus.c" // target: 'http://dev.admin.carrots.ptteng.com', //源地址 // changeOrigin: true, //改变源 // pathRewrite: { // '^/api': 'http://dev.admin.carrots.ptteng.com' //路径重写 // } // } // } // }修改后需重启服务后生效
可以在vue项目中引入如下组件进行测试
需要安装axios,npm install --save-dev axios
<template> <div id="example-2"> <!-- `post` 是在下面定义的方法名 --> <button v-on:click="post">登录</button> <p></p> </div> </template> <script> import axios from 'axios' export default { name: "Ajax", data() { return {} }, methods: { post() { axios.post('/api/a/login?name=admin&pwd=123456', { }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); } }, } </script> <style scoped> </style>package.json文件,仅供参考
{ "name": "hello-world", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint" }, "dependencies": { "core-js": "^3.3.2", "vue": "^2.6.10" }, "devDependencies": { "@vue/cli-plugin-babel": "^4.0.0", "@vue/cli-plugin-eslint": "^4.0.0", "@vue/cli-service": "^4.0.0", "axios": "^0.19.0", "babel-eslint": "^10.0.3", "eslint": "^5.16.0", "eslint-plugin-vue": "^5.0.0", "vue-template-compiler": "^2.6.10" }, "eslintConfig": { "root": true, "env": { "node": true }, "extends": [ "plugin:vue/essential", "eslint:recommended" ], "rules": { "no-console": 1 }, "parserOptions": { "parser": "babel-eslint" } }, "postcss": { "plugins": { "autoprefixer": {} } }, "browserslist": [ "> 1%", "last 2 versions" ] }vue跨域方案指北
VUE CLI 3 配置
Webpack-dev-server的proxy用法