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)
    })
  }
}

运行后发现调用成功

相关推荐
用户298698530143 小时前
在 React 中使用 JavaScript 将 Excel 转换为 SVG
前端·javascript·react.js
labixiong3 小时前
手写Promise--微任务、静态方法、async/await 全搞懂(三)
前端·javascript
铁皮饭盒5 小时前
3行代码搞定页面截图,Bun.WebView真的简单
javascript
kyriewen18 小时前
我手写了一个 EventEmitter,面试官追问了 6 个问题——第 4 个我没答上来
前端·javascript·面试
山河木马19 小时前
矩阵专题2-怎么创建视图矩阵(uViewMatrix)
javascript·webgl·计算机图形学
the_answer19 小时前
Webpack vs Vite 深度对比分析
前端·webpack
tangdou36909865520 小时前
AI真好玩系列-2分钟快速了解DeepAgents | Quick Guide to DeepAgents in 2 Minutes
前端·javascript·后端
张元清20 小时前
React useIntersectionObserver Hook:懒加载与可见性检测(2026)
javascript·react.js
彭于晏爱编程20 小时前
纯 JS + Node,一个下午手搓了能读懂公司代码的 AI 助手,老板以为我转行了
前端·javascript
妙码生花21 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十四):眨眼小人登录页制作
前端·javascript·ai编程