node.js - Node adding additional brackets to json post body -
im sending post requests .net application node rest api controller named 'createpdf'
the .net code im using send post requests seems working fine, im creating json object using serializeobject , using urlencode encode json , sending off in post request.
dim postjson string = jsonconvert.serializeobject(article) dim request webrequest = webrequest.create("url") request.method = "post" dim postdata string = webutility.urlencode(postjson) dim bytearray byte() = encoding.utf8.getbytes(postdata) request.contenttype = "application/x-www-form-urlencoded" //go off , send post request
this seems produce valid json in format -
{ "source": "le sauce", "subtopic": "le subtopic", "title": "le title", "body": "le body", "refs": "le refs", "lastupdated": "19/12/2016 11:23:56" }
but when send json , try , parse json code below in node controller seems add additional brackets , colons json.
node controller
var express = require('express'); var router = express.router(); var bodyparser = require('body-parser'); var fs = require("fs"); var wkhtmltopdf = require('wkhtmltopdf'); router.use(bodyparser.urlencoded({ extended: true })); router.post('/', function(req, res) { console.log(req.body); res.status(200).send('lol'); }); module.exports = router;
and invalid json output console.log(req.body)
{ '{ "source”:”le sauce“, ”subtopic”:”le subtopic“, ”title”:”le title“, ”body”:”le body“, ”refs”:”le refs“, ”lastupdated":"19/12/2016 11:23:56" }': '' }
for reason brackets, colons, quotes, etc have been added json @ point , made json invalid, im pretty sure not happening on .net side , must happening when node tries handle post request cant figure out where.
any ideas how resolve ?
if you're sending json, incorrect:
request.contenttype = "application/x-www-form-urlencoded"
as on server side:
router.use(bodyparser.urlencoded({ extended: true }));
that quite says you're sending uri-encoded form data, not json, , telling body-parser
decode uri-encoded form data, not json.
send right content type:
request.contenttype = "application/json"
...and use right parser:
router.use(bodyparser.json());
(note can use multiple parsers if have endpoints expect uri-encoded form data , others expect json; body-parser
figure out content type.)
Comments
Post a Comment