Undefined variable Express Js - Node JS - javascript

I want to build an API with node js.
i post the data using postman.
I don't know why, every time I post the data, I got nothing.
Here is my code :
let router = require('express').Router();
let bodyParser = require('body-parser');
let db = require('./queries');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: false }));
router.post('/test', function (req, res) {
res.send('post data ' + req.body.clinic_name)
});
req.body.clinic_name has no value, thats why it will undefined data.
i try clinic_name, address, phone, and fax. all of them returning undefined data.
please help me to fix this issue.
thank you.

use the "application/x-www-form-urlencoded" tab in POSTMAN or you can make sure your client has header '"Content-Type: "application/json"', and send a raw json

Problem is that you have sent the data res.send('welcome, ' + req.body.clinic_name) first and then printing in console.log(req.body);
It should be like
console.log(req.body);
res.send('welcome, ' + req.body.clinic_name)

Related

What's the NodeJS / Express equivalent to PHP's file_get_contents('php://input')?

In PHP I can fetch incoming JSON from let's say an AJAX request by calling file_get_contents('php://input'), I'm now rebuilding my API in NodeJS (TypeScript) and am looking for an equivalent to fetch incoming JSON.
Various web searches did not deliver what I was looing for, so I hope to find help here.
You can try to call the correct URL by using Axios. Following this link https://www.npmjs.com/package/axios for more.
You can use bodyparser for express and receive data via post.
let app = express();
const bodyParser = require("body-parser");
app.listen(port);
console.log('API started port' + port);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/path', "maybe cors()", function(req, res){
let data = req.body.data //data is the json you get
}
Thats the way i fetch json that gets send to the server. Hope you can make something with it.

Cannot GET / while using a grammar Api

I am trying to use API to check the grammar of the sentence. but when I don't know it is giving me the error Cannot GET / please tell me where I am wrong.
const express = require('express');
const https = require('https');
const app = express();
app.get('/', function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
const text = req.body.cityName;
const url = "https://www.stands4.com/services/v2/grammar.php?uid=8816&tokenid=u9K3iEcIcjmS84B6&text=" + text + "&format=json";
https.get(url,function(response){
response.on("data", function(data){
const grammar = JSON.parse(data);
const fault = grammar.matches.message;
console.log(fault);
res.write("<p>The problem in text :" + fault + "</p>");
res.send();
});
});
});
app.listen(port = 3000, function(){
console.log("Server is running on port 3000 ");
})
Are you trying to access localhost:3000 via the browser? if so you're using app.post change it to app.get
This error usually occurs when target an invalid endpoint, make sure that you use correct url and correct method
Your controller is a POST controller thus the error. You either do a post call or you change to the controller to GET.
app.get("/", function(req, res) ...
If you are trying to hit your own API, then the problem is that your controller is being a POST controller. That is why it throws you Cannot GET.
You can change app.post to app.get or, you can try calling POST method instead of GET.

Express.js + body-parser: empty req.body from POST request

I am using Express and body-parser middleware to process incoming requests. On the front end, I have a form that's just a hidden input and a submit button (written in Pug):
form(notes="saveNotesForm" action=`/lessons/${lesson._id}/notes` method="POST" enctype="application/x-www-form-urlencoded")
input(type="hidden" id="hiddenNotes" name="hiddenNotes" alt="Notes Copy" value="test").notesHidden
input(type="submit" name="saveNotes" alt="Save Notes" value="Save")
On the backend, I have the Express app using body-parser:
const bodyParser = require('body-parser');
// ...
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
And the route processing the incoming request:
router.post('/lessons/:lessonID/notes', lessonController.updateNotes);
// ... and in lessonController:
exports.updateNotes = async (req, res) => {
console.log('updateNotes request received');
console.log(req.body);
res.status(200).json({ status: 'success' });
}
When I try to use req.body in updateNotes, the body is an empty object, but should at least have the property hiddenNotes with the value "test". Please comment if you have any questions or think you see the problem!
[UPDATED]
This was a silly mistake, I forgot I had written a separate event handler for when this form gets submitted - it just took me posting on SO before I went through all of my code :) The event handler uses axios and looks like this:
const SaveNotesButton = $('form.saveNotes');
SaveNotesButton.on('submit', ajaxSaveNotes);
function ajaxSaveNotes(e) {
e.preventDefault();
axios
.post(this.action)
.then(res => {
console.log(res.data);
})
.catch(console.error);
}
Unfortunately, when making posts with axios, you need to include the data in an object like this, or else it won't be included in the request:
const SaveNotesButton = $('form.saveNotes');
SaveNotesButton.on('submit', ajaxSaveNotes);
function ajaxSaveNotes(e) {
e.preventDefault();
axios
.post(this.action, { notes: this.children.hiddenNotes.value }) // Data added here
.then(res => {
console.log(res.data);
})
.catch(console.error);
}
Have to tried querying your end point using Postman or something similar?
There could be one possible explanation for why your req.body is undefined. Are you sure your app.use(bodyParser.json()) and app.use(bodyParser.url... are written before your app.use('***', router) lines? If you put the body parser middleware AFTER your router middleware it essentially won't get called because middleware are called in the order they are put in app.use. So you should place your bodyParser before all your router logic. BodyParser middleware then calls all the other middleware (with the req.body populated) that come after it including all your router level middleware.
Hope it helps!
Not sure how you are defining your routes but I would expect a post route to look like the following:
const express = require('express');
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.post('/lessons/:lessonID/notes', (req, res) => {
// now pass the req object to your function
lessonController.updateNotes(req);
});
You need to pass the req object to your function to be able to access req.body...

Node.js unable to read POST JSON data in my webhook

I have a node.js + Express application. It has a webhook that I have provided to a third party service. The service sends a POST request to my webhook with JSON body which looks something like this:
{"split_info" : "null", "customerName" : "Merchant Name",
"additionalCharges" : "null", "paymentMode":"CC",
"hash":"a31ff1b91fd9b8ae9c82f38b02348d21fsdfd86cc828ac9a0acf82050996372cc656de3db0fe3bf9af52b73a182a77787241f3e19ec893391607301b03e70db8",
"status" : "Release Payment", "paymentId" : "551731" ,
"productInfo":"productInfo", "customerEmail":"test#gmail.com",
"customerPhone":"9876543212", "merchantTransactionId":"jnn",
"amount":"100.0", "udf2":"null", "notificationId" :"4", "udf1":"null",
"udf5":"null", "udf4":"null", "udf3":"null","error_Message":"No
Error"}
I am using body-parser module to read POST data. However when I do req.body it gives [object Object], if I do JSON.stringify(req.body), it gives {} i.e. empty. If I try to access the keys in the response like req.body.paymentMode then it gives undefined.
Here is my router code for the webhook: mywebhook.js
var express = require('express');
var router = express.Router();
router.post('/success', function(req, res){
//this is where I need to strip the JSON request
//req.body or JSON.stringify(req.body) or anything that works
//if everything is okay then I send
res.sendStatus(200);
});
module.exports = router;
My app.js looks like this:
var express = require('express');
var exphbs = require('express-handlebars');
var router = express.Router();
var bodyParser = require('body-parser');
var mywebhook = require('./routes/mywebhook');
var app = express();
.
.
.
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use('/callwebhook', mywebhook);
.
.
.
so on
Pretty sure I am missing something or doing something wrong, but I am not able to figure it out.
Thanks.
I finally found what was going on.
The way the body-parser works is that it will only try to parse a request in which they understand the Content-Type. This is mainly so you can stack them (app.use multiple parser types without conflict) and also because you typically don't want to parse a request that's going to fail (Content-Type: text/html is unlikely to ever get through a JSON.parse, for example).
I ended up getting sent */*; charset=UTF-8 which is not even a valid Content-Type header value period. The body-parser module refused to accept it, since that is gibberish. This module does allow you to setup a function that lets you put any custom logic you want to perform the filtering.
I had to put the body parser in my router code just for this webhook case.
var bodyParser = require('body-parser');
var customParser = bodyParser.json({type: function(req) {
return req.headers['content-type'] === '*/*; charset=UTF-8';
}});
router.post('/success', customParser, function(req, res){
console.log(JSON.stringify(req.body));
});
#svens thank you for your help.

I can't get data from req.body in nodesjs + expressjs

This is my code:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/',function(req,res){
res.sendfile("index.html");
});
app.post('/login',function(req,res){
console.log(req.body)
var user_name=req.body.user;
var password=req.body.password;
console.log("User name = "+user_name+", password is "+password);
res.end("yes");
});
app.listen(3000,function(){
console.log("Started on PORT 3000");
})
I set a console in post method function but it displayed:
{}
User name = undefined, password is undefined
I couldn't get any data from response. I had lookup doc but I couldn't find any error. I don't still understand. What mistake did i make?
You should send your data using Postman with the content-type:application/json in the header. This will ensure that the server receives the data in JSON format.
I know what happens!
If I want to send data in form-data, here has good solution helps me:
Result is undefined when I use form-data in Postman
If I use x-www-form-urlencoded to send data, it's actually valid!
I find when postman send json data without content-type:application/json in headers, it's definitely error. Now, I have added it. It can be valid.
Thanks, everyone!

Categories