vue2的webpack(vue.config.js) 怎么使用请求转发 devServer.proxy

首先用 express 搭建后端服务器,注意使用中间件解析json格式的请求体,才会获取到 post 参数

复制代码
app.use(express.json());

app.js

复制代码
const express = require('express')
const app = express()
app.use(express.json());
const port = 3000

app.post('/api/vue2', (req, res) => {
  console.log(req.body)
  res.header('Access-Control-Allow-Origin','*')
  res.send({ss: req.body})
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

node app.js 启动服务

vue.config.js

复制代码
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000'
      }
    }
  }
})

main.js

复制代码
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'

Vue.config.productionTip = false
Vue.prototype.$axios = axios

new Vue({
  render: h => h(App),
}).$mount('#app')

App.vue

复制代码
export default {
  name: 'App',
  components: {
    HelloWorld
  },
  mounted() {
    console.log('mounted')
    this.$axios({
      method: 'post',
      url: '/api/vue2',
      data: {
        aa: 'test1',
        bb: 'test2'
      }
    }).then(res => {
      console.log('res', res)
    })
  }
}

运行后发现调用成功

相关推荐
五仁火烧15 小时前
Vue3 项目的默认端口行为
服务器·vue.js·nginx·容器·vue
fengbizhe15 小时前
bootstrapTable转DataTables,并给有着tfoot的DataTables加滚动条
javascript·bootstrap
刘一说15 小时前
TypeScript 与 JavaScript:现代前端开发的双子星
javascript·ubuntu·typescript
EndingCoder16 小时前
类的继承和多态
linux·运维·前端·javascript·ubuntu·typescript
用户479492835691516 小时前
React 终于出手了:彻底终结 useEffect 的"闭包陷阱"
前端·javascript·react.js
Younglina16 小时前
一个纯前端的网站集合管理工具
前端·vue.js·chrome
木头程序员16 小时前
前端(包含HTML/JavaScript/DOM/BOM/jQuery)基础-暴力复习篇
开发语言·前端·javascript·ecmascript·es6·jquery·html5
哈__16 小时前
React Native 鸿蒙跨平台开发:PixelRatio 实现鸿蒙端图片的高清显示
javascript·react native·react.js
wszy180917 小时前
外部链接跳转:从 App 打开浏览器的正确姿势
java·javascript·react native·react.js·harmonyos
pas13617 小时前
31-mini-vue 更新element的children
前端·javascript·vue.js