fetch请求的两种传输方法,以及node.js 后端,解析方法时需要

本文介绍了在Node.js后端如何解析fetch请求,特别是json和form两种格式的数据。通过使用中间件body-parser进行安装配置,解析不同Content-Type类型的数据。文章提到了fetch作为异步请求的解决方案,并提供了json和form格式的前端传输示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

node.js后端:

后端传来的数据需要解析一下:使用中间件body-parser

安装方法:(在项目里)

npm 
install body-parser

在后台index.js文件里:

//为保险起见先安装body-parser; npm 
install body-parser

//再引入bodyParser 中间件

const bodyParser=require('body-parser')
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())

这两行意思是解析两种后台传来的数据,一个种是form格式的,一个是json格式的,还可以解析其他两个格的数据。一共四种格式,常用的就是form和json格式的

四种常见的Content-Type类型

application/json //json格式的数据
application/x-www-form-urlencoded//form格式的数据
application/form-data//文件提交
text/xml //xml格式的,用的不多

说一下常见的两种类型json和form格式的前端传输方法

以fatch为例:

为什么用fetch?

fetch+await是解决异步请求的终极解决方案(个人观点)简单明了,出自ES 2017

fetch:

直接代码:

json格式传参

(async () => {
        let data = {
            "username": "张三",
            "password": "123"
        };
        let res = await fetch('http://localhost:3000/login', {
            method: 'post',
            headers: {
                "Content-Type": "application/json;charset=utf-8"
            },
            body: JSON.stringify(data)
        });
        let result = await res.json()
        console.log(result)

    })()

这个是前端用json格式传输的,所以后台一定要写:app.use(bodyParser.json()),意思是开启对json数据的解析

from格式传参

(async ()=>{
        let res=await fetch('http://localhost:3000/login',{
            method:"post",
            headers:{
                "Content-Type":"application/x-www-form-urlencoded"
            },
            body:"username=张三&password=123"
        })
        let result=await res.json()
        console.log(result)
    })()

两种格式的body写法是不一样的

以上有错误欢迎指正

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值