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

来源:互联网 发布:书店网络推广 编辑:程序博客网 时间:2024/06/05 15:14

初始化

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

0 0