简体   繁体   中英

NodeJS post rest api issue

i want to create a post request from ajax to node.js but i can't do it.

My Server code is ;

var app = require('express')();
var qs = require('querystring');

app.post("/example",function (req,res) {
    if(req.method=='POST') {
        var body='';
        req.on('data', function (data) {
            body +=data;
        });
        req.on('end',function(){
            var POST =  qs.parse(body);
            console.log(POST);
            console.log(body);
        });
    }

    res.end("basarili");
});

Its mine javascript client code

$.post("URL",{type:1,value:"Usage"},function(res){console.log(res)});

But i get console log on client like this.

------WebKitFormBoundary372H6vQd8ECcu8cz Content-Disposition: form-data; name="type"

1 ------WebKitFormBoundary372H6vQd8ECcu8cz

Can anyone help me ?

First, install the body-parase package from npm.

npm install body-parser --save

2) Second, add these lines to your code

var bodyParse = require("body-parser");
.....
app.use(bodyParser.json());       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({   // to support URL-encoded bodies
        extended: true}));`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM