express中间件body-parser实现拿到post请求的数据

初始化

npm init   //一直回车

安装express

npm install express --save

安装body-parser

npm install body-parser --save

app.js

'use strict';

let express = require('express') ;
let app = express() ;
let bodyParser = require('body-parser') ;
let fs = require('fs') ;


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


app.get('/idx',function( req , res ){
  fs.readFile('./views/ajax.html','utf8',function(err,data){
    res.end( data ) ;
  })
}) ;


app.post('/ajax' , function( req , res ){
  console.log( 'ajax' , req.body );
  res.end('{"msg":"请求成功"}')  //回应浏览器
}) ;


app.listen(9091,'127.0.0.1',function(){
  console.log('server is running at port 9091') ;
});

ajax.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>form</title>
</head>
<body>

  <button id="btn">ajax按钮</button>

<script>

var btn = document.getElementById('btn') ;

btn.onclick = function(){
  var xhr = new XMLHttpRequest() ;
  xhr.open( 'post' , '/ajax') ;
  xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded') ;
  xhr.send('name=jim&age=18') ;
  xhr.onreadystatechange = function(){
    if( xhr.status == 200 && xhr.readyState == 4 ){
      var content = xhr.responseText ;
      console.log( JSON.parse(content) )   //
    }
  }
}


</script>

</body>
</html>

在浏览器输入网址http://127.0.0.1:9091/idx

点击按钮发送数据

图片.png

控制台

打印req.body

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值