使用的是vue2
解决方法:
在vue.config,js中加入proxy配置:
devServer: { proxy:{ '/api':{ target:'http://localhost:3000',//填写后台接口地址 changeOrigin:true,//设置允许跨域 pathRewrite: { '^/api': '/' } } }, port: port, open: true, overlay: { warnings: false, errors: true }, before: require('./mock/mock-server.js') },
main.js中设置了如下:
import axios from 'axios' Vue.prototype.$axios = axios //配置请求的跟路径 axios.defaults.baseURL='/api'
接下来就是vue组件中,编辑点击提交按钮axios:
methods: { onSubmit() { let formData = new FormData(); for(var key in this.form){ formData.append(key,this.form[key]); } axios({ method:"post", url:"/api/form/post", headers: { "Content-Type": "multipart/form-data", "Access-Control-Allow-Origin":"*" }, withCredentials:true, data:formData }).then((res)=>{ console.log(res); }); //this.$message('你点击了提交按钮!') //console.log(this.form.name,this.form.region,this.form.desc) }, onCancel() { this.$message({ message: '你点击了取消按钮!', type: 'warning' }) } }
node后端提供了接口:
//新手村的菜单获取 var express = require('express'); var router = express.Router(); //post请求测试 router.post('/post',function(req,res,next){ res.send("你好,这里是表单提交请求,我是post请求") }) module.exports = router;
node的app.js引入路由:
var form = require('./routes/form') var app = express(); //设置跨域问题解决方案 app.all('*', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS'); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header('Access-Control-Allow-Headers', ['mytoken','Content-Type']); next(); }); //引入各个路由的api app.use('/', indexRouter); app.use('/users', usersRouter); app.use('/api/novice', novice); app.use('/api/form',form);
再次运行代码,完成,不再报错了: