I'm attempting to extract a part of an HTTP POST Request Body and log it to my console using nodejs. Here is what I have so far:
const express = require('express');
const request = require('request');
const bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json);
app.listen(PORT, function () {
console.log("Example app listening on port " + PORT);
});
app.post('/events', function(req, res) {
console.log(req.body);
});
I'm trying to log the 'challenge' value:
POST
"body": {
"type": "url_verification",
"token": "0Rwv2qjMozpy9MSHWM2jKf0q",
"challenge": "sW6u5bGBluzxVR79Inv04HlLGdrSxZttZ0dJrUF4E4smD8RWmbkU"
}
You will just reference the challenge field from the body
consoe.log(req.body.challenge)
Related
I understand what the req and res objects contain, what they are used for, and when they are created, but I was wondering how they are created.
The req and res objects that you are referring to come from an npm package called express. Express is a lightweight package that allows you to handle HTTP requests on your node server.
Below is a small example of how to use the package with some example HTTP endpoints.
In the example, I also use a package called 'body-parser' this package is used to parse any HTTP requests with a JSON body. The package puts the parsed body into the req object at the key body, as can be seen in the code example.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
// Handle GET / request here
});
app.post('/', (req, res) => {
// Handle POST / request here
// Get body of request
var body = req.body;
});
app.listen(8080, () => console.log('Listening on port 8080'));
req and res are the component of Express framework of Node package manager(npm) and is used to respond as per the request created by the user.
//To print Date as string
const express = require("express");
const bodyparser = require("body-Parser");
const app = express();
app.get("/", function(req, res) {
var today = new Date();
var options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
var day = today.toLocaleDateString("en-US", options);
res.render("list", {
kindOfDay: day
});
});
app.post("/", function(req, res) {
var item = req.body.selectSection;
items.push(item);
res.redirect("/");
});
app.listen("3000", function() {
console.log(" the server is runnimg in port 3000");
});
I can not retrieve route parameters with a simple express.Router() in an web app.
Here is a minimal example:
var http = require('http');
const express = require('express');
const app = express();
app.use('/hello/:world', express.Router()
.get('/', function (req, res) {
console.log("hello : ", req.params); //
res.status(200).send({status: 'success', params: req.params});
}));
var port = process.env.PORT || 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
I don't get any error, the res.params is simply empty when I try to reach:
http://localhost:3000/hello/100 for example.
Here is the response:
{
"status": "success",
"params": {}
}
What I have tried so far is to set express.Router({ params: 'inherit' })
as told here: https://github.com/expressjs/express/issues/2151#issuecomment-44716623 but it doesn't change anything.
And here is the manual: http://expressjs.com/en/guide/routing.html
Answer:
The thing that finally worked for me, based on these:
API doc :http://expressjs.com/en/api.html
SO example: Express Router undefined params with router.use when split across files
is to set express.Router({mergeParams: true}).
So:
var http = require('http');
const express = require('express');
const app = express();
app.use('/hello/:world', express.Router({mergeParams: true})
.get('/', function (req, res) {
console.log("hello : ", req.params); //
res.status(200).send({status: 'success', params: req.params});
}));
var port = process.env.PORT || 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
Is giving the following response over http://localhost:3000/hello/10
{
"status": "success",
"params": {
"world": "10"
}
}
I am trying to post data from postman to my node server, I keep getting 404.
Is my code setup correctly to receive post to http://localhost:8080/back-end/test and if not how can I fix it ?
var express = require('express');
var request = require('request');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var rp = require('request-promise');
var app = express();
var port = process.env.PORT || 8080;
// Start the server
app.listen(port);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
console.log('Test server started! At http://localhost:' + port); // Confirms server start
var firstFunction = function () {
return new Promise (function (resolve) {
setTimeout(function () {
app.post('back-end/test.js', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
}, 2000);
});
};
I am posting LoginEmail and keep getting 404.
Move app.post() outside of the timeout, promise, and firstFunction.
There is no proceeding paths defined in your code, so the path must start with a /: /back-end/test.js. Don't forget the extension since you've defined it.
The body parser body is {}. I've already done research and made sure that my ajax data key is set correctly as well as make sure the middleware is set up correctly as well. Here is my frontend ajax call
$.ajax({
type:"GET",
url:"/api",
data: {course:"MATH-226"},
success: function(data){ alert(data);}
});
And here is my backend server.js file:
'use strict'
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const alg = require('./app/algorithm.js');
const app = express();
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/api', (req, res) => {
console.log(req.body);
alg.create(req.body.course, answer => res.send(answer));
});
let server = app.listen(3000, () => {
let host = server.address().address;
let port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
You are using a GET request, so it's probably not being sent. If you need to send something, you can attach it as a header or include it in the query string of the url. If you want to send data, I would use a POST request.
Check out this article
How to send data in request body with a GET when using jQuery $.ajax()
I am trying to make POST work with Express (4.13.3 version). when I print request.body.user, it says 'undefined'. I am using Chrome Poster to post my JSON request. Here is how my request looks
{
"user":"testUser",
"password":"test pwd"
}
the URL I use: http://localhost:4000/first
and my server.js file.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/first', function (request, response) {
console.log('FIRST POST hello world');
console.log('req.body:' + request);
var user_name=request.body.user;
var password=request.body.password;
console.log("User name = "+user_name+", password is "+password);
response.end("yes");
});
var server = app.listen(4000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
when I post the request, here is what I see on my Node console.
Example app listening at http://:::4000
FIRST POST hello world
req.body:[object Object]
User name = undefined, password is undefined
Why I am not able to get my 'user' and 'password' values here from my request? I am getting 'undefined' for both of these variables.
try this:
app.use(bodyParser());
if this still doesn't work change your request to this:
user=testUser&password=test+pwd
This is how the request body have to look using Chrome's "Advanced REST Client".