I have this route:
var express = require('express');
var multer = require('multer');
const upload = multer();
module.exports = (function () {
var router = express.Router();
router.post('/avatar/:user', upload.single('avatar'), function (req, res, next) {
var file = req.file; // file passed from client
var meta = req.body; // all other values passed from the client, like name, etc..
console.log(file);
console.log(meta);
res.json({
success: true
});
});
return router;
})();
And when I try to post to it using Postman with header 'Content-Type : application/x-www-form-urlencoded' and in body 'form-data' File (image), the express crashes with error:
Error
at readStream (F:\Web\WorkoutFocus_Server\node_modules\raw-body\index.js:196
:17)
at getRawBody (F:\Web\WorkoutFocus_Server\node_modules\raw-body\index.js:106
:12)
at read (F:\Web\WorkoutFocus_Server\node_modules\body-parser\lib\read.js:76:
3)
at urlencodedParser (F:\Web\WorkoutFocus_Server\node_modules\body-parser\lib
\types\urlencoded.js:115:5)
at Layer.handle [as handle_request] (F:\Web\WorkoutFocus_Server\node_modules
\express\lib\router\layer.js:95:5)
at trim_prefix (F:\Web\WorkoutFocus_Server\node_modules\express\lib\router\i
ndex.js:317:13)
at F:\Web\WorkoutFocus_Server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (F:\Web\WorkoutFocus_Server\node_modules\express\
lib\router\index.js:335:12)
at next (F:\Web\WorkoutFocus_Server\node_modules\express\lib\router\index.js
:275:10)
at jsonParser (F:\Web\WorkoutFocus_Server\node_modules\body-parser\lib\types
\json.js:112:7)
at Layer.handle [as handle_request] (F:\Web\WorkoutFocus_Server\node_modules
\express\lib\router\layer.js:95:5)
at trim_prefix (F:\Web\WorkoutFocus_Server\node_modules\express\lib\router\i
ndex.js:317:13)
at F:\Web\WorkoutFocus_Server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (F:\Web\WorkoutFocus_Server\node_modules\express\
lib\router\index.js:335:12)
at next (F:\Web\WorkoutFocus_Server\node_modules\express\lib\router\index.js
:275:10)
at cors (F:\Web\WorkoutFocus_Server\node_modules\cors\lib\index.js:185:7)
Does this have something to do with file size or multipart/form-data perhaps?
I tried to set the bodyparser.json limit to '50mb', but no difference.
Related
I got "TypeError: res.send is not a function" this error in the given code
const express = require('express');
const bodyParser=require('body-parser');
const app=express();
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/' , (req , res)=>{
res.sendFile(__dirname+"/index.html")
})
app.post('/' , (req , res)=>{
// console.log(req.body);
var num1=req.body.num1;
var num2=req.body.num2;
var res=num1+num2;
res.send('Ans is: '+res);
});
app.listen(3000,function(){
console.log('running');
});
plzz help me to fix this :(
and the error looks like this:-
TypeError: res.send is not a function
at C:\Users\ADMIN\Desktop\calculator\calculator.js:16:8
at Layer.handle [as handle_request] (C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\index.js:275:10)
at C:\Users\ADMIN\Desktop\calculator\node_modules\body-parser\lib\read.js:130:5
at invokeCallback (C:\Users\ADMIN\Desktop\calculator\node_modules\raw-body\index.js:224:16)
You overwrite res with your own local variable:
var res=num1+num2;
This "shadows" the res in your function declaration.
you just override res again in the above line..
var res=num1+num2;
change this to anything else like
var result =num1+num2;
res.send('Ans is: '+result);
Using Angular and Nodejs as backend. csurf middleware throws Forbidden error, even if see the same _csrf token in the request cookie. My URL is: https://192.168.0.100.xip.io:64726/
Error log:
method is GET url is /
{"G_ENABLED_IDPS":"google","G_AUTHUSER_H":"0","_csrf":"XcUDRcxDPpje0nlNGdF4bZpn"}
method is POST url is /api/login/verify
{"G_ENABLED_IDPS":"google","G_AUTHUSER_H":"0","_csrf":"XcUDRcxDPpje0nlNGdF4bZpn"}
ForbiddenError: invalid csrf token
at csrf (/Users/admin/nodejs/google-signin-server/node_modules/csurf/index.js:112:19)
at Layer.handle [as handle_request] (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/route.js:137:13)
at urlencodedParser (/Users/admin/nodejs/google-signin-server/node_modules/body-parser/lib/types/urlencoded.js:100:7)
at Layer.handle [as handle_request] (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/layer.js:95:5)
at /Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/index.js:335:12)
Nodejs:
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
const bodyParser = require('body-parser')
const helmet = require("helmet");
// var session = require('express-session')
const uuid = require('uuid/v4');
const app = express()
const parseForm = bodyParser.urlencoded({ extended: false });
const csrfProtection = csrf({cookie:true,secure:true,httpOnly:false})
app.use(cookieParser())
app.use((req, res, next) => {
const { method, url } = req;
console.log(" method is "+ method + " url is " + url)
logger.info('cookie', req.cookies)
next()
})
app.get('/', csrfProtection, function(req, res) {
console.log('app // get called')
// Pass the Csrf Token
tokenVal = req.csrfToken();
res.json({csrfToken: tokenVal });
res.sendFile('index.html');
});
app.post('/api/login/verify',parseForm, csrfProtection,(req, res) => {
verify(req.body.idToken)
.then((result) => {
let id = result['sub']
logger.info('id=', id)
res.send({
'payload': result
})
}).catch(logger.error)
});
I am getting an error and that error is
TypeError: req.status is not a function
at E:\Creations\Languages\HTml\HTML\experiment\app.js:11:6
at Layer.handle [as handle_request] (E:\Creations\Languages\HTml\HTML\experiment\node_modules\express\lib\router\layer.js:95:5)
at next (E:\Creations\Languages\HTml\HTML\experiment\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (E:\Creations\Languages\HTml\HTML\experiment\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\Creations\Languages\HTml\HTML\experiment\node_modules\express\lib\router\layer.js:95:5)
at E:\Creations\Languages\HTml\HTML\experiment\node_modules\express\lib\router\index.js:281:22
at Function.process_params (E:\Creations\Languages\HTml\HTML\experiment\node_modules\express\lib\router\index.js:335:12)
at next (E:\Creations\Languages\HTml\HTML\experiment\node_modules\express\lib\router\index.js:275:10)
at expressInit (E:\Creations\Languages\HTml\HTML\experiment\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (E:\Creations\Languages\HTml\HTML\experiment\node_modules\express\lib\router\layer.js:95:5)
And the code in which i am getting error is:
const express = require('express');
const path = require('path');
const app = express();
const port = 8000;
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
And the directory in which i am working, in that directory i have installed express, pug, nodemon. If anybody knows what to do let me know in the comments or answer
app.get("/demo", (req, res) => {
res.status(200).render('demo', {title: 'Hey there!', message: 'Kya chal raha hai'})
});
app.get("/", (req, res) => {
res.send("<p>Rocket Launched succesfully<br></p>")
});
app.get("/about", (req, res) => {
res.send("<p>About<br>We are human being</p>")
});
app.listen(port, () => {
console.log(`Listening on ${port}`);
});
You have a typo, you type req intead res somewhere. Req object really doesnt have status method
My code:
var express = require("express");
var bodyParser = require("body-parser");
var multer = require("multer");
var fs = require("fs");
var ejs = require('ejs');
var app = express();
var upload = multer({ dest: 'uploads/' })
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', function(req, res){
console.log('Works');
res.render('index');
});
app.post('/', upload.single('test'), function (req, res, next) {
var raw = new Buffer(req.file.buffer.toString(), 'base64');
fs.writeFile('./uploads/upload.png', raw, function (err) {
if (err) {
console.log('Error');
return next(err);
}
res.end('Success!');
});
});
var server = app.listen(3000, function() {
console.log("Listening on port %s...", server.address().port);});
My error:
TypeError: Cannot read property 'buffer' of undefined
at /Users/jacob/nodejs-prj/polyglotdev-test/app.js:27:33
at Layer.handle [as handle_request] (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/route.js:137:13)
at multerMiddleware (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/multer/lib/make-middleware.js:18:41)
at Layer.handle [as handle_request] (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/layer.js:95:5)
at /Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/index.js:335:12)
I have to receive image file as base64 format from rasperry pi. Then i have to decode it back to image and save it in mongo db.
I was trying to send some test data with postman to my endpoint. But always this error occurs.
In Postman it looks likes this:
Screenshot of postman
Try this:
var upload = multer({
dest: 'uploads/',
storage: multer.memoryStorage()
});
I solved this problem. Forget about my 'index.ejs' file, there's a tag ''. Attribute 'name="test"' must be equal to argument in "upload.single('test')".
I am trying to create a server for an app with a node JS server on AWS(not sure how relevant that is) and I am testing it with Postman. For some reason my hello world function, which is just a GET works perfectly but my POST to create a user keeps giving me this error:
TypeError: Cannot read property 'username' of undefined
at app.get.params.QueueUrl (/home/ec2-user/Outfitr/Server/index.js:40:29)
at Layer.handle [as handle_request] (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/layer.js:82:5)
at next (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/route.js:110:13)
at Route.dispatch (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/route.js:91:3)
at Layer.handle [as handle_request] (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/layer.js:82:5)
at /home/ec2-user/Outfitr/Server/node_modules/express/lib/router/index.js:267:22
at Function.proto.process_params (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/index.js:321:12)
at next (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/index.js:261:10)
at serveStatic (/home/ec2-user/Outfitr/Server/node_modules/express/node_modules/serve-static/index.js:59:14)
at Layer.handle [as handle_request] (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/layer.js:82:5)
Here is my code:
var express = require("express")
var app = express();
var gm = require("gm");
var fs = require("fs");
var async = require("async");
var s3 = new AWS.S3();
// set the region for the AWS API requests
AWS.config.region = 'us-west-2';
var DAO_QUEUE_URL = 'https://sqs.us-west-2.amazonaws.com/275333356355/DAO-Queue';
app.set('port', (process.env.PORT || 8080 ));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
response.send('Hello World (Finally)');
});
app.post('/create_user', function( request, response) {
process.stdout.write("WTF");
create_user( request.body.username, request.body.password, request.body.firstname, request.body.lastname, request.body.gender, request.body.latitude,
request.body.longitude, request.body.description, request.body.city,
request.body.state_province, request.body.country, request.body.email,
request.body.phone_number);
response.send('IT WORKED!');
});
function create_user( username, password, firstname, lastname, is_brand, gender,
description, city, state_province, country, birthday) {
messageBody = {"username":username, "password":password, "firstname": firstname,
"lastname":lastname, "is_brand":is_brand, "gender":gender, "city":city,
"state-province":state_province, "country":country, "birthday":birtyhday};
queueUrl = DAO_QUEUE_URL;
sendSQSMessage( JSON.stringify(messageBody),queueUrl);
}
What could be wrong?
Make sure that you are using the x-www-form-urlencoded tab in postman. I've fallen for that a few times.
Also, make sure you are using the body-parser package.
var express = require("express")
var app = express();
var gm = require("gm");
var fs = require("fs");
var async = require("async");
var bodyParser = require('body-parser');
var s3 = new AWS.S3();
// set the region for the AWS API requests
AWS.config.region = 'us-west-2';
var DAO_QUEUE_URL = 'https://sqs.us-west-2.amazonaws.com/275333356355/DAO-Queue';
// Add the middleware
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.set('port', (process.env.PORT || 8080 ));
app.use(express.static(__dirname + '/public'));
So I think that you are getting the error because there is no middleware setting up a req.body object for you, bodyParser should do the trick.