Express: express.json() or express.urlencoded() does not work - json

If I write post request like this:
app.post('/sendCoins', [express.urlencoded(), express.json()], function(req, res) {
//console.log(req.body.toAddress);
console.log(req.body.amount);
console.log(JSON.stringify(req.body));
res.send('hi');
});
console prints undefined.
But when I use express.bodyParser() application starts with connect.multipart() wanring but prints the request properly.
"123"
{"amount":"123","toAddress":"99999999"}
As per express documentation I should not use express.bodyParser()

Related

Pretty print the JSON returned by express in Node.JS

I'm trying to follow this great design recommendation documentation for my server development in Node.JS regarding the JSON pretty formatting when returning it to the caller.
I can't figure out to do so when returning a file though:
app.get('/data.txt', function(req, res){
return res.sendFile(path.resolve(__dirname + '/views/myData.json'));
});
Would you have any suggestion?
You can simply require the JSON file using :
let fileContents = require(path.resolve(__dirname + '/views/myData.json'));
And then
app.get('/data.txt', function(req, res){
return res.send(fileContents);
});
Note: This approach doesn't send the file.It sends the contents of the JSON file in response.

Server not returning JSON from Express to React (proxy)

I'm attempting to make an application that has a React frontend (running on port 8080) and an Express-Node.js backend (on port 3000). I'd like for my client to use fetch to request data from my server. So far, what I've read online indicates that I need to add a proxy entry to my package.json with the value of http://localhost:3000. I've done this, my server receives the request correctly, but its response is not what I expect (a JSON object). What am I doing wrong?
//Server
app.get('/search', function(req, res) {
...
//console.log(section) <-- Is the correct value
res.json(section);
})
...
app.listen(3000)
//Client
handleTouchTap() {
fetch('/search?crn=10001').then(function(response) { //<-- Hard-coded for testing
return response; //<-- Does not contain the value of "section" from server
}).then(function(data) {
console.log(data); //<-- Likewise, does not contain the value
});
}
//From package.json
...
"proxy": "http://localhost:3000",
...
You need to pull the json out of your response:
fetch('/search?crn=10001')
.then(response => response.json())
.then(section => console.log(section));

Node.js: How to exchange a JSON object [duplicate]

This question already has answers here:
How to access POST form fields in Express
(24 answers)
Closed 6 years ago.
My purpose is to send a JSON object from the client-side to the server. So taking into account the following details of the client:
<script>
var onClickFunct = function() {
trial1.send({
"test": $("#input_test").val(),
});
}
</script>
Where input_test is the name of my tag in the html page.
And where trial1 is implemented with the following code:
var trial1 = {
//notifica al server una nuova registrazione
send: function(data){
$.getJSON('/tst',data);
}
}
My Server can't see the object; infact if I print req.params it shows me "undefined".
app.get('/tst',function(req){
console.log(req.params);
});
My index.html reuire the following script <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
While the server require only express
Try changing:
app.get('/tst',function(req){
console.log(req.params);
});
to:
app.get('/tst',function(req){
console.log(req.query);
});
The req.params is for parameters in your routes, like:
app.get('/test/:name', function (req, res) {
console.log(req.params);
});
When you access /test/abc then the req.params.name will be "abc".
The $.getJSON() sends the data as query parameters, see:
http://api.jquery.com/jquery.getjson/
And for the query parameters you use res.query.
If it was a POST request and you wanted to access parameters passed in the request body then you would user req.body (but you would need to use a bodyParser middleware).
Remember to use GET only for reading operations, where in the query parameters you specify what you want to get or in what form, what order etc.
If you pass data to store in a database or something like that then use POST or PUT for that and pass the data in the request body (which can be JSON).
$ npm install --save body-parser
and then:
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
your endpoint should look like this:
app.post('/tst',function(req){
console.log(req.body);
});
then use Jquery Post:
$.post('/tst',data);
body parser install example taken from here:
How to retrieve POST query parameters?
hope it helps :)

express-session + express res.render throwing "TypeError: Converting circular structure to JSON"

I have an Express JS app that uses express-session for session management.
I am trying to save some values to session in controller A and consume them in controller B, and send them as context to a template like so:
controllerA: function(req, res, next) {
req.session.context = {
id: '123123123',
phone: '09998889999'
};
return res.redirect(res.locals.pathFor('verifications#phoneVerify'));
}
:
:
:
controllerB: function(req, res, next) {
//Some code here
return res.render('templatepath/template', req.session.context);
}
The problem is, that when I do this, I get an error at the template render step saying:
TypeError: Converting circular structure to JSON
If I instead do this as:
req.session.id: '123123123',
req.session.phone: '09998889999';
The code works just fine. Does express-session have an issue with objects?

mocha - send json to post express route

I'm trying to send some json data to my '/sign_up' route in mocha test.
request = require 'supertest'
express = require 'express'
app = express()
Authentication = require("#{specDir}/../apps/authentication/routes")
authenticate = new Authentication app
Factory = require "#{specDir}/factories/user"
user = Factory.build 'user'
it 'creates an account', (done) ->
request(app).post('/sign_up').set('Accept', 'application/json').send(user).end (err, res) ->
expect(res.statusCode).to.equal 200
done()
However req.body in the callback function is undefined. Below I've shown a snippet of my route callback
#app.post '/sign_up', (req, res) ->
res.format
html: -> res.status(406).send 'invalid Content-Type'
json: ->
console.log req.body
res.status(200).send status: 'ok'
Probably I'm missing some small detail, but can't see what.. any ideas?
P.S. I'm well aware of that the tests pass and it does what it should, but before I move on to write more tests I gotta know how to send some data.
You're missing a body parser, add app.use(express.json()) in your code somewhere.