ajax的post方法相比get方法,在传参形式上很不一样, get把参数用'?'拼接在端口后,并且用'&'连接;而post则是需要在send参数里设置.

根据ajax实例xhr.setRequestHeader('content-type', )中第二个参数的不同,  send的参数也不相同.

最常用的有两种: application/x-www-form-encoded 和 application/json两种形式.  

1
       const username = document.getElementById('username').value,
       password = document.getElementById("password").value;

var xhr = new XMLHttpRequest(); 2 xhr.open('POST','/test'); 3 // xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); 4 // xhr.send(`name=${username}&&password=${password}`); 5 xhr.setRequestHeader('content-type', 'application/json'); 6 xhr.send(JSON.stringify({username, password}))

express本身只能用get方法,对用post方法的请求, 没法查看request的啥. 所以用第三方插件body-parser;

 1 const bodyParser = require('body-parser');
 2 const app = express();
 3 // var urlencodedParser = bodyParser.urlencoded({ extended: false });
 4 // app.post('/test',urlencodedParser,(req,res)=>{
 5 //     console.log(req.body)
 6 // })
 7 
 8 var jsonParser = bodyParser.json();
 9 app.post('/test',jsonParser,(req,res)=>{
10     console.log(req.body)
11 })

 

相关文章:

  • 2021-10-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-16
  • 2022-02-21
  • 2021-08-25
  • 2022-12-23
猜你喜欢
  • 2021-12-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-20
  • 2021-09-22
  • 2022-12-23
相关资源
相似解决方案