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写法是不一样的
以上有错误欢迎指正