How to iterate over body of POST request in Express.js? - javascript

I'm constructing a generic route handler for POST requests in NodeJS.
I need to iterate over the req.params of the POST request, without knowing beforehand what the parameters are.
I have tried the following without success:
console.log("checking param keys...")
Object.keys(req.param).forEach(function(key){
console.log(key +"is " + req.params(key) )
})
When I run this code, only the "Checking param keys..." gets printed.
Anybody knows how to do this?

I guess you're asking how to iterate form post from a url encoded POST request body, so it is bodyParser() middleware that did your trick.
req.params is an array that contains properties mapped by routing defined express app. see details from req.params, not the request body. Take the follow code for example:
var app = require("express")();
app.use(express.bodyParser());
app.post("/form/:name", function(req, res) {
console.log(req.params);
console.log(req.body);
console.log(req.query);
res.send("ok");
});
Then test it like this:
$ curl -X POST --data 'foo=bar' http://localhost:3000/form/form1?url=/abc
You will see the console output like this:
[ name: 'form1' ]
{ foo: 'bar' }
{ url: '/abc' }
So req.body is the right way to access request body, req.query is for read query string of all HTTP methods.

Related

node server cannot find the data in the body

i am sending a post request from fetch but the nodejs server is not able to access the body from the post request. I tried req.body but it just returns empty brackets.
const express = require('express');
const bodyParser=require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json());
app.use(express.json());
app.get("/user",function(req,res){
res.send("just Checking");
});
app.post("/user", (req, res) => {
console.log(req.body);
res.send("got the data");
});
app.listen(3000,function(res){
console.log("server is workig a t local host 3000");
});
This is the browser side code
const checking = { name:"badmintion" }
function yo (){
fetch("/user",{
method : "POST",
Headers : {
'Content-Type':'application/json'
},
body: JSON.stringify(checking)
})
}
yo();
In the browser i can see that the data is being sent but i am unable to recieve the in the nodejs server it just shows empty brackets.
Edit: I was able to recreate the server code locally on my machine. I didn't find any issues. I used Postman to send the JSON to the /user route. The issue you might be having is in the front end.
Headers should be lowercase. You have capitalized it:
...
fetch("/user",{
method : "POST",
headers : {
...
}
...
Make sure you're sending data in a JSON format so that express can parse it into object:
To avoid any conflict for (parse json) better that remove body parser completely and try again.
For request, according to stanley, headers set as lowercase. Its will be work.
This tutorial maybe help u:
https://www.geeksforgeeks.org/express-js-express-json-function/amp/

Request post return an empty object in NODE.JS

I don't know why but i try to send an object in my back. I can find good information in my network's payload but my req.body return everytime an empty object
my probleme
add app.use(express.json());
express.json() is a middleware that allows express to recognise the json data in request object.
Also your controller is not sending any response back, for that use:
app.post("/", (req, res) => {
res.status(200).json({"data" : req.body});
}

Request to API based on URL/

I'm attempting to make a request to an API to get a users' avatar. This is the code I have, however it's returning a "player is not defined" error.
app.get(`/api/avatar/${player}`, function(req, res) {
res.redirect(`http://cdn.simulping.com/v1/users/${player}/avatar`);
});
Essentially, if the URL is /api/avatar/3925 it would send them to http://cdn.simulping.com/v1/users/3925/avatar.
Assuming you're using Express.JS for the routing, the correct way for doing that is:
app.get('/api/avatar/:id', function(req, res) {
res.redirect(`http://cdn.simulping.com/v1/users/${req.params.id}/avatar`);
})
Assuming you are using Express routing, then you would need to utilise route parameters.
The Express documentation provides:
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.
In this case:
Route path: /api/avatar/:player
Request URL: http://localhost:3000/api/avatar/3925
req.params: { "player": "3925" }
The working code:
app.get('/api/avatar/:player', function(req, res) {
res.redirect(`http://cdn.simulping.com/v1/users/${req.params.player}/avatar`);
});
You can read more about it in the Route Parameters section of the Express Routing Guide.

How to use ? as separator in webservice url

using nodejs / express, i'm trying to make a webservice using ? to separate url from parameters and then & as parameters separators.
when using this, it works
app.get("/tableref/:event/:queryObject", function(req, res) {})
or this one works also
app.get("/tableref:event&:queryObject", function(req, res) {})
but not this, I got 404 error:
app.get("/tableref?:event&:queryObject", function(req, res) {})
It seems that it is the ? that is the problem. Is there a way to authorize it? escape it?
I'd like to use express validator like this
Thanks
To get value from query string you don't need to specify those query string parameters in Express routes.
Your code should look like this
app.get("/tableref", function(req, res) {
res.json(req.query)
});
when you enter the URL localhost/tableref?hello&world you will get the response {"hello": "", "world": ""}
and if you want to pass data to query string variables, you can also enter the URL localhost/tableref?hello=world&foo=bar and you will get the response {"hello": "world", "foo": "bar"}

I use routes in my Node.JS app and when I try to open one of the routes from the browser I get an error

That's my app. When I try to open ip/delete I get an error
Cannot GET /delete
I'm following this tutorial, https://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function(req, res) {
console.log("Got a GET request");
res.send('GBArena Labs');
})
app.post('/', function(req, res) {
console.log("Got a POST request");
})
app.delete('/delete', function(req, res) {
res.send('Delete');
console.log("Got a DELTE request");
})
app.listen(8081);
You can't navigate to a DELETE. You have to send a DELETE request. In example :
<a href="/delete">My delete link<a/> will be sent as a GET request and not a DELETE.
In order to hit your delete endpoint, you would have to use a ajax library like jquery $.ajax and using
$.ajax({
url: '/delete',
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
from the client side.
There are many ways, but i would suggest you looking into : HTTP verbs
You may need to call the route without the /delete and use the HTTP verb DELETE from a REST client such as Fiddler or Postman.
First, you try to access by ip/delete endpoint. I assume you will get an error because you are not using the port of the application (you have to access by ip:port/delete)
You have to know about the usage of DELETE method. When you try to directly access the ip/delete endpoint, your browser will set it as GET method while in your application, there is not GET method for ip/delete

Categories

Resources