路虽远 行则将至

Lee


  • 主页
  • 归档
  • 分类
  • 标签
  •   

站点访客数   人

站点浏览量   次

本页浏览量   次

© 2024 辣辣辣白菜

Theme Typography by Makito

Proudly published with Hexo

Vite配置代理、x-www-form-urlencode请求处理

Posted at 2022-05-22 解决问题  前端 vue 

跨域问题解决

编辑 vite.config.js,添加

  server: {
    proxy: {
      "/api": {
        target: "http://localhost:7001",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },

其中,target 为后端地址,修改后,在 Vue 眼中后端地址就是http://localhost:3000/api/,所有的请求都到这个地址。

POST 请求发送 x-www-form-urlencode

如下,这是一个登录表单。

form:{
    username: 'admin',
    password: '123456'
}

我需要发送到后端,后端使用的是x-www-form-urlencode的Content-Type,但是不经过 qs 的 stringify,发送过去是这样的:

[Object: null prototype] { '{username:'admin',password:'123456'}': '' }

也就是说后端把整个对象当做了对象第一个字段的名字。

我们需要在项目下安装 qs,并在发送请求的页面引入:

npm i qs

import qs from 'qs';

发送请求是这样的:

API.post("/user/login", qs.stringify(this.form)).then((res) => {});

(封装的格式可能各不相同,只需将原本要发送的this.form使用 qs 格式化一下,即qs.stringify(this.form)即可。)

공유하기 

 이전 포스트: 使用 Vue + Electron 构建桌面应用 다음 포스트: Vue3.0全局事件总线 

站点访客数   人

站点浏览量   次

本页浏览量   次

© 2024 辣辣辣白菜

Theme Typography by Makito

Proudly published with Hexo