后端接口要求请求头的Content-Type:application/x-www-form-urlencoded
背景#
使用apipost接口请求工具调试后端接口的时候,后端要求的类型是application/x-www-form-urlencoded
,采用其他方式无法获取到数据,前端如何发起网络请求呢?
以类型为application/x-www-form-urlencoded
发起请求
基础知识#
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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)