get data from client with regional language in nodejs - node.js

client side data sample as below
{name:'ABC',age:24,language:'ಕನ್ನಡ'}
i need to send language value to another service
but in node console cannot print as above
instead of ಕನ್ನಡ it prints like {name:'ABC',age:24,language:'����ͷ�'}
my express setup like
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json({
limit: '2mb'
}));
app.use(bodyParser.urlencoded({
limit: '900kb',
extended: true
}));
app.use((req, res, next) => {
req.header("Content-Type", "application/json;charset=UTF-8");
next();
});
this is indian kannada language.I try with locale module but no luck.
how to set accept-language please help me to solve

Use req.headers["accept-language"] to get the language the user has set in his browser.
For easier support look into a locale module.

I am not sure whether this will help you or not but I just gave it a try:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json({
limit: '2mb'
}));
app.use(bodyParser.urlencoded({
limit: '900kb',
extended: true
}));
app.use((req, res, next) => {
console.log(decodeURIComponent(req.body.data));
req.header("Content-Type", "application/json;charset=UTF-8");
next();
});
app.listen(3000);
before posting it:
encodeURIComponent('ಕನ್ನಡ'); // returns %E0%B2%95%E0%B2%A8%E0%B3%8D%E0%B2%A8%E0%B2%A1
then try:
curl -d "data=%E0%B2%95%E0%B2%A8%E0%B3%8D%E0%B2%A8%E0%B2%A1" http://localhost:3000/
it will print on console:
ಕನ್ನಡ
P.S. As I mentioned this is just one possible way so there might be other ways as well.

Related

Getting body-Parser is deprecated Warning In Vs code and not Able to get Body tried to use inbuilt body-parser of express

Below Is Code Of app.js file
var port = process.env.PORT || 8080; // set our port
var express = require('express');
var app = express();
var bodyParser = require('body-parser')
var cors = require('cors');
var indexRouter = require("./server/routes/index");
var http = require('http').Server(app);
const path = require('path')
const Licence = require('./server/CronJob/CronJob');
http.listen(port);
app.use(cors());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.json({
type: 'application/vnd.api+json'
}));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit: 50000
}));
// parse application/json
app.use(express.json());
app.use(express.urlencoded()); //Parse URL-encoded bodies
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
res.header("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0");
next();
});
app.use(express.static(path.join(__dirname, "/build")));
app.use(indexRouter);
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, '/build/index.html'), function (err) {
if (err) {
res.status(500).send(err)
}
})
})
// Licence.licenceExpire();
console.log('Magic happens on port ' + port); // shoutout to the user
exports = module.exports = app;
Version
express: ^4.17.1,
body-parser: ^1.19.0
and also used suggestion given in below blog
update
I have used inbuilt body-parser but getting same error again here is the screenshot of function of inbuilt body-parser
From 4.16.0+ body-parser is inbuilt in express
Use http://expressjs.com/en/api.html#express.json
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded())
https://expressjs.com/en/changelog/4x.html#4.16.0
The express.json() and express.urlencoded() middleware have been added to provide request body parsing support out-of-the-box. This uses the expressjs/body-parser module module underneath, so apps that are currently requiring the module separately can switch to the built-in parsers.
https://github.com/expressjs/body-parser/commit/b7420f8dc5c8b17a277c9e50d72bbaf3086a3900
This deprecates the generic bodyParser() middleware export that
parses both json and urlencoded. The "all" middleware is very
confusing, because it makes it sound like it parses all bodyes,
though it does not do multipart, which is a common body type. Also,
the arguments for the two different middleware are starting to
overlap and it's hard to configure then when done this way.
If you are using this code
app.use(bodyParser.urlencoded({extended: true}));
then you can replace this code with
app.use(express.urlencoded());
and if you are using
app.use(bodyParser.json());
then replace with
app.use(express.json());
Don't use body-parser
Getting request body is now builtin with express So, you can simply use
app.use(express.json()) //For JSON requests
app.use(express.urlencoded({extended: true}));
directly from express
You can uninstall body-parser using npm uninstall body-parser
Then you can simply get the POST content from req.body
app.post("/yourpath", (req, res)=>{
var postData = req.body;
//Or just like this, for string JSON body
var postData = JSON.parse(req.body);
});

Node js, Express - Unable to retrieve form data using post method

My application has post route that accepts the data from postman client. I have written following code to retrieve value of form and print it:
var express = require('express');
req.app.use(express.urlencoded());
req.app.use(express.json());
console.log('req.body.name --> ' + req.body.name);
Above code prints req.body.name --> undefined rather than name value given in field name
I also tried following code:
var express = require('express');
const bodyParser = require('body-parser');
req.app.use(bodyParser.urlencoded({ extended: true }));
console.log('req.body.name --> ' + req.body.name);
Above code too prints req.body.name --> undefined rather than name value given in field name.
Can anyone please guide me on to resolve the issue in retrieving field name?
Used multer to solve this based on inputs from req.body is empty on express POST call.
Posting to benefit others.
var multer = require('multer');
var upload = multer() ;
app.post('/test', upload.array(), function (req, res, next) {
console.log(req.body.name);
});
Cheers :)
In your code, req is used, but req is not declared.
You wrote that you used POST, but you didn't write an entry point for POST.
Please try the following code:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ extended: true }));
app.post('/users', (req, res) => {
console.log(req.body);
console.log(req.body.name);
res.send(req.body.name);
});
app.listen(3000);
The port number is not necessarily 3000.
Use your Postman configuration.
In your code, proper imports are not there.
1. For Any node application these imports are mandatory
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
2. Use these imports properly like
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ extended: true }));
3. Then use any Http Method like Get, Post, Put, and Delete
Example -
app.post(‘/sample’, (req, res) => {
// name must be in your request body while requesting for the above API
console.log(req.body.name);
res.send(req.body.name);
});
4. Add the port lister on which Application should run
app.listen(9000);

How to use `bodyParser.raw()` to get raw body?

I am creating a web API using Express.
The feature is to allow API users to send a file to the server.
Here's my app setup code:
var express = require('express');
var path = require('path');
// ...
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
// API routes
var images = require('./routes/api/img');
var app = express();
app.use(bodyParser.raw());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/api', images);
// ...
module.exports = app;
Please notice that I am using app.use(bodyParser.raw());.
How do I get the raw bytes from POST requests?
const express = require('express');
const router = express.Router();
/* POST api/img */
router.post('/img', function(req, res, next) {
// how do I get the raw bytes?
});
module.exports = router;
if you want to send a raw data and get with body parser you just configure this way:
app.use(bodyParser.raw({ inflate: true, limit: '100kb', type: 'text/xml' }));
That behavior doesn't corrupt the body content.
To parse all content types I use:
app.use(
express.raw({
inflate: true,
limit: '50mb',
type: () => true, // this matches all content types
})
);
To get the raw body in just a single route:
app.put('/upload', express.raw({ inflate: true, limit: '50mb', type: () => true }), async (req, res) => {
res.json({ bodySize: req.body.length });
});
In that case note that the previously app.use()'d body parsers (json for example) are executed first - so check that req.body is indeed a Buffer, otherwise a malicious caller could send something like {"length":9999999} with Content-Type: application/json.
The parsed body should be set on req.body.
Keep in mind that middleware is applied in the order you set it with app.use, my understanding is that applying the bodyParser multiple times as you have will attempt to parse the body in that order, leaving you with the result of the last middleware to operate on req.body, i.e. since both bodyParser.json() and bodyParser.raw() both accept any inputs, you will actually end up attempting to parse everything from a Buffer into JSON.

The JSON data in request body is not getting parsed using body-parser

When I send a POST request using postman to localhost:8080/api/newUser with request body:
{name: "Harry Potter"}
At server end console.log(req.body) prints:
{ '{name: "Harry Potter"}': '' }
server.js
var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
app.use('/', express.static(__dirname));
router.use(function(req, res, next) {
next();
});
router
.route('/newUser')
.post(function(req, res) {
console.log(req.body);
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
app.use('/api', router);
app.listen(8080);
What am I doing wrong?
In express.js the order in which you declare middleware is very important. bodyParser middleware must be defined early than your own middleware (api endpoints).
var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
app.use('/', express.static(__dirname));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
router
.route('/newUser')
.post(function(req, res) {
console.log(req.body);
});
app.use('/api', router);
app.listen(8080);
Change the request header
'Content-Type':'application/json'
So that bodyParser can parse the body.
*That is what works for me. i am using angular 2+ with express(body-parser)
I spent quite a bit of time trying to figure out how to pass objects from Axios as key-value pairs and eventually decided to go with an alternative because setting the Content-Type: "application/json" retuned an empty object.
If the above options don't work for you, I would consider:
Extracting the key (which should contain the entire
object)
Parsing the key
Accessing the values of the newly created objects
This worked for me:
var obj = (Object.keys(req.body)[0])
var NewObj = JSON.parse(obj)
var name = apiWords["Key1"]
var image = apiWords["Key2"]

ExpressJS Error: Body-Parser Deprecated

Question
I'm trying build a Node.js API, when write my server.js file, my code looks like this:
var express = require('express');
var express = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.get('/api/posts', function(req,res) {
res.json([
{
username: 'oscar',
body: 'hello'
}
])
})
app.listen(3000, function() {
console.log('Server Listening on', 3000)
})
However, in the command prompt I am getting this error:
body-parser deprecated bodyParser: use individual json.urlencoded
middlewares server.js:4:11
body-parser deprecated undefined extended: provide extended option
node_modules\body-parser\index.js:85:29
I tried changing this to :
app.use(bodyParser.urlencoded({ extended: true }));
and
app.use(bodyParser.urlencoded({ extended: false }))
like other posts suggest, but it still gives the same error. Not sure what to do now! Please help.
Thanks!
var app = express();
// configure body-parser
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
I had similar deprecated warning. Here's my original code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
Adding {extended: true} fixed the warning for me. Here's changed code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
Unless you have a typo, change:
var express = require('body-parser');
var app = express();
app.use(bodyParser.json());
to:
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
Do have a look at what the request and response objects do here
You don't actually need the line app.use(bodyParser.urlencoded({extended: true}));
I've got it to work with the following code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
As log as you have app.user(bodyParser.json()); you shouldn't get the error.
You don't need body-parser module any more with current express.js versions (≥ 4.16).
Instead, use the json parser already included in express:
app.use(express.json())
Source: https://expressjs.com/en/changelog/4x.html#4.16.0
Don't use body-parser
In new versions of express, body parsing is now builtin. So, you can simply use
app.use(express.json()) //For JSON requests
app.use(express.urlencoded({extended: true}));
from directly express
You can uninstall body-parser using npm uninstall body-parser
Then you can simply get the POST content from req.body
app.post("/yourpath", (req, res)=>{
var postData = req.body;
//Or for string JSON body, you can use this
var postData = JSON.parse(req.body);
});

Resources