Loading

后端接口要求请求头的Content-Type:application/x-www-form-urlencoded

背景

使用apipost接口请求工具调试后端接口的时候,后端要求的类型是application/x-www-form-urlencoded,采用其他方式无法获取到数据,前端如何发起网络请求呢?

以类型为application/x-www-form-urlencoded发起请求

以其他类型如:form-data发起请求

基础知识

application/x-www-form-urlencoded是常见的web 表单提交方式,参数通常在请求body中以key=value&key=value将键值对的参数用&连接起来方式传递。

服务端代码

以下采用node的express框架设置

const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.send("ok");
});

// 设置x-www-form-urlencoded方式解析
app.use(express.urlencoded({ extended: false }));

app.post("/test", (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.send(req.body);
});

app.listen(8081, () => {
  console.log("server is running at http://localhost:8081");
});

前端可采用的方式

方式1:表单

 <form action="http://localhost:8081/test" method="post">
      <input type="text" name="name" value="xm" />
      <input type="text" name="age" value="20" />
      <input type="submit" value="提交" />
    </form>

上面点击提交后可以正确的返回服务端的数据

控制台结果

服务端响应结果

方式2: axios请求

有的时候我们不是采用表单的方式,我们需要通过第三方库axios按照后端的接口方式来请求数据

方式a:使用URLSearchParams来构建参数

async created() {
    const params = new URLSearchParams()
    params.append('username', 'zs')
    params.append('password', '456')

    const result = await this.$http.post('http://localhost:8081/test', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    })

    console.log(result)
  },

效果图:

方式b:使用qs来构建参数

const qs = require('qs')
export default {
  data() {
    return {
      result: '',
    }
  },
  async created() {
    const result = await this.$http.post(
      'http://localhost:8081/test',
      qs.stringify({ name: 'hahah', age: 66 }),
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      }
    )

    console.log(result)
  },
}
</script>

参考文章

https://blog.csdn.net/haozi_love/article/details/123292203

posted @ 2022-12-01 23:44  ^Mao^  阅读(1284)  评论(0编辑  收藏  举报