how to print the data from post request on console

前端 未结 6 1024
忘掉有多难
忘掉有多难 2021-02-18 16:07

I am trying to print the post data on my console


app.js

var express = require(\'express\')
 , http = require(\'http\');

var app         


        
相关标签:
6条回答
  • 2021-02-18 16:39

    Use built in function "util" to print any type of json data in express js

    var util = require("util");
    console.log(util.inspect(myObject, {showHidden: false, depth: null}));
    
    0 讨论(0)
  • 2021-02-18 16:43
    var express = require('express');
    var app = express();
    
    app.use(express.bodyParser());
    
    app.post('/post/', function(req, res) {
       // print to console
       console.log(req.body);
    
       // just call res.end(), or show as string on web
       res.send(JSON.stringify(req.body, null, 4));
    });
    
    app.listen(7002);
    
    0 讨论(0)
  • 2021-02-18 16:47

    Use request.query when you have querystring params.

    For form/post data use req.body.

    In your case, use request.body.key.

    0 讨论(0)
  • 2021-02-18 16:59

    An update on using the middleware, body-parser, for later versions of Express: Using app.use(express.bodyParser()) will report an error such as: Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.

    This can be addressed by first installing the body-parser middleware:

    npm install body-parser
    

    then write code such as:

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

    and then accessing the body of the request object, for example, console.log(req.body)

    0 讨论(0)
  • 2021-02-18 16:59

    You can't call app.use(express.bodyParser()); inside middleware/route handler:

    • request should pass through bodyParser() before it reaches route handler
    • you will be adding new bodyParser()s in each request, but they will be after app.router and will never work
    0 讨论(0)
  • 2021-02-18 17:02

    Instead of query:

    var keyName=request.query.Key;
       console.log(keyName);
    

    use body:

    var keyName1=request.body.key;
    console.log(keyName1);
    

    Code:

    var express = require('express')
     , async = require('async')
     , http = require('http');
    
    var app = express();
    
    app.set('port', process.env.PORT || 7002);
    
    app.use(express.static(__dirname + '/public/images'));
    
    app.use(express.bodyParser());
    
    app.post('/Details/',function(request,response,next){
    
       var keyName1=request.body.key;
       console.log(keyName1);
    } );
    
    
    http.createServer(app).listen(app.get('port'), function(){
     console.log('Express server listening on port ' + app.get('port'));
    });
    
    0 讨论(0)
提交回复
热议问题