Cant able to handle request in nodejs - node.js

In my express application I am getting following error while getting request from user. No issue if request body is ib JSON format
UnsupportedMediaTypeError: unsupported charset "ISO-8859-1"
at urlencodedParser (/var/www/payment/node_modules/body-parser/lib/types/urlencoded.js:108:12)
at Layer.handle [as handle_request] (/var/www/payment/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/var/www/payment/node_modules/express/lib/router/index.js:317:13)
at /var/www/payment/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/var/www/payment/node_modules/express/lib/router/index.js:335:12)
at next (/var/www/payment/node_modules/express/lib/router/index.js:275:10)
at IncomingMessage.<anonymous> (/var/www/payment/gate.js:392:5)
at IncomingMessage.emit (events.js:159:13)
at endReadableNT (_stream_readable.js:1054:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11
)
I already set this in my code
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));

body-parser docs say:
Returns middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.
I would try disabling (commenting out in your code) the bodyParser.urlencoded parser.

Related

How to use more than one middleware in expressjs?

I am trying to use 2 middlewares for my route, auth.js and authAdmin.js which are in different folder.
var middleware = [auth, authAdmin]
router.get("/all_infor", middleware, userCtrl.getUsersAllInfor)
Official page of Expressjs defined the same way I did above but I am getting error:
F:\Mern projects\full_auth\node_modules\express\lib\router\route.js:202
throw new Error(msg);
^
Error: Route.get() requires a callback function but got a [object Object]
at Route.<computed> [as get] (F:\Mern
projects\full_auth\node_modules\express\lib\router\route.js:202:15)
at Function.proto.<computed> [as get] (F:\Mern
projects\full_auth\node_modules\express\lib\router\index.js:510:19)
at Object.<anonymous> (F:\Mern projects\full_auth\routes\userRouter.js:25:8)
can any one suggest how do I fix this? Thank You in advance.

Express URIError: Failed to decode param

I'm using next.js with a custom express server when the params of a request contains % it causes this error:
URIError: Failed to decode param '%%faker'
at decodeURIComponent (<anonymous>)
at decode_param (D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\router\layer.js:172:12)
at Layer.match (D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\router\layer.js:148:15)
at matchLayer (D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\router\index.js:574:18)
at next (D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\router\index.js:220:15)
at middleware (D:\ahmed\coding\react js\with-redux-app\node_modules\http-proxy-middleware\lib\index.js:43:7)
at Layer.handle [as handle_request] (D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\router\index.js:317:13)
at D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\router\index.js:335:12)
at next (D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\router\index.js:275:10)
at expressInit (D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\router\index.js:317:13)
at D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:\ahmed\coding\react js\with-redux-app\node_modules\express\lib\router\index.js:335:12)
for example if the request is http://localhost:3000/summoner/eune/%%faker the error happens but if it's http://localhost:3000/summoner/eune/^^faker the ^^ gets encoded and the url becomes http://localhost:3000/summoner/eune/%5E%5Efaker and everything works perfectly.i could fix this error by following this answer Express handling URIError: Failed to decode param like so:
server.use((err, req, res, next) => {
if (err instanceof URIError) {
err.message = "Failed to decode param: " + req.url;
err.status = err.statusCode = 400;
console.log(err);
return res.redirect(`http://${req.get("Host")}${req.url}`);
// return app.render(req, res, "/_error");
}
});
return res.redirect(`http://${req.get("Host")}${req.url}`); this will redirect the user from http://localhost:3000/summoner/eune/%%faker to http://localhost:3000/summoner/eune/%25%25faker and if i use return app.render(req, res, "/_error"); it will send the default error page provided by next.js back to user but this is not what i want. I want to handle the % like ^.
so my questions are:
why the % doesn't get encoded to %25 and if there is a way to make it happen?
who is responsible for encoding the browser or express?
what is the best way to handle this error?
I'm using node v8.9.1, express ^4.16.3.
Please, make the answer detailed i'm a beginner developer.
Thanks for your time.
Like you pointed out, urls are percent-encoded and http://localhost:3000/summoner/eune/%%faker is just not valid as an url.
When you type an invalid url, most browsers are kind enough to change it to something valid, ex: http://localhost:3000/test test is automatically changed to http://localhost:3000/test%20test, but it's just a fallback to avoid too many errors.
In your case, % is not automatically changed to %25 because browsers cannot know when to substitute % and when to leave it. Ex: when you type %25%25faker, should this url be used as is or should it be replaced to %2525%2525faker ?
In summary: You must use valid urls at any point in time and not rely on browser kindness.

unsupported charset "ISO-8859-1" in nodejs

In my nodeJS application I used following line of code to get req.body
app.use(bodyParser.urlencoded({
extended: false
}));
This is working fine, but one request to my application throws following error:
UnsupportedMediaTypeError: unsupported charset "ISO-8859-1"
at urlencodedParser (/var/www/payment/node_modules/body-parser/lib/types/urlencoded.js:108:12)
at Layer.handle [as handle_request] (/var/www/payment/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/var/www/payment/node_modules/express/lib/router/index.js:317:13)
at /var/www/payment/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/var/www/payment/node_modules/express/lib/router/index.js:335:12)
at next (/var/www/payment/node_modules/express/lib/router/index.js:275:10)
at jsonParser (/var/www/payment/node_modules/body-parser/lib/types/json.js:118:7)
at Layer.handle [as handle_request] (/var/www/payment/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/var/www/payment/node_modules/express/lib/router/index.js:317:13)
at /var/www/payment/node_modules/express/lib/router/index.js:284:7
If I remove the previous line, then it works for that request, but in all other requests, I am unable to retrieve data. Is there any way to fix this?
You can modify the original request header, to UTF-8.
I found no easy way to intercept the urlencoded parser, so i just changed the encoding to utf8

NodeJS Express Server crashes when router gets an encoded URL

I have a NodeJS and an API that handles get requests.
...
var apiRoutes = express.Router();
apiRoutes.get("/filter/:name",function(req, res){
// do something
res.json(result);
}
app.use('/api', apiRoutes);
Then in the client (not an important information but it is Angular2):
find(name:string): void{
name.trim();
this.http.get(encodeURI('http://server_address/api/filter/' + name))...
It works well for the parameters don't contain whitespaces, etc. In order to make it working with spaced inputs also, I used encodeURI function. However, when I give an input with whitespaces the server gives error:
undefined:0
^
SyntaxError: Unexpected end of input
at Object.parse (native)
at IncomingMessage.<anonymous> (/user/home/server/server.js:65:28)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
Any idea what can I do to fix it?
I figured out the problem. I was doing something like:
apiRoutes.get("/filter/:name",function(req, res){
http.request(anotherURL + req.body.name)...
}
And thought that the name parameter is already encoded since it was encoded in the client. However I see that I have to encode it in the server again.
apiRoutes.get("/filter/:name",function(req, res){
http.request(anotherURL + encodeURI(req.body.name))...
}

nodejs express session error

I wrote a demo website with nodejs. In file app.js I used express.session
Case 1:
app.use(express.cookieParser())
app.use(express.session({ secret: "whatever" }));
//this code is working
Case 2:
app.use(express.session({ secret: "whatever" }));
app.use(express.cookieParser());
//this is not correct
The error log is:
Express
500 TypeError: Cannot read property 'connect.sid' of undefined
at Object.session [as handle] (D:\web\nodejs\Weibo\node_modules\express\node_modules\connect\lib\middleware\session.js:239:32)
at next (D:\web\nodejs\Weibo\node_modules\express\node_modules\connect\lib\proto.js:193:15)
at Object.favicon [as handle] (D:\web\nodejs\Weibo\node_modules\express\node_modules\connect\lib\middleware\favicon.js:77:7)
at next (D:\web\nodejs\Weibo\node_modules\express\node_modules\connect\lib\proto.js:193:15)
at Object.handle (D:\web\nodejs\Weibo\node_modules\express-partials\index.js:94:5)
at next (D:\web\nodejs\Weibo\node_modules\express\node_modules\connect\lib\proto.js:193:15)
at Object.expressInit [as handle] (D:\web\nodejs\Weibo\node_modules\express\lib\middleware.js:30:5)
at next (D:\web\nodejs\Weibo\node_modules\express\node_modules\connect\lib\proto.js:193:15)
at Object.query [as handle] (D:\web\nodejs\Weibo\node_modules\express\node_modules\connect\lib\middleware\query.js:44:5)
at next (D:\web\nodejs\Weibo\node_modules\express\node_modules\connect\lib\proto.js:193:15)
Middleware order matter in Express, as they are executed in the order you defined them. In your case, the cookieParser middleware adds some information that is used by the session middleware.
You can check connect's documentation:
Session data is not saved in the cookie itself, however
cookies are used, so we must use the cookieParser()
middleware before session().

Resources