I'm new to nodejs and express and I can't seem to phantom as per why this method isn't resolved in Webstorm. The .get method returns fine, testing it with the .all method works fine aswell. I have no clue why the .post method is unresolved, node starts up fine but if I try to send a post request to it through Postman it just gives an error:
the Postman error
app.js
'use strict';
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var routes = require("./routes");
app.use(function (req, res, next) {
console.log(`${req.method} ${req.originalUrl}`);
next();
});
app.use(bodyParser.json());
app.use("/questions", routes);
// routes(app);
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log("Express is running at", port);
});
routes.js
'use strict';
var express = require("express");
var router = express.Router();
// GET /questions
// Route for getting all questions
router.get("/", function (req, res) {
res.json({
response: "You sent me an awesome GET request, thank you!"
});
});
// POST /questions
// Route for creating a question
router.post("/questions", function (req, res) {
res.json({
response: "You sent me an awesome POST request, thank you!"
});
body: req.body;
});
module.exports = router;
package.json
{
"name": "02-express-api",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.15.2",
"express": "^4.13.4"
}
}
router.post("/questions", should be router.post("/", for this to work; right now, that handler is responding to the URI /questions/questions since the router itself gets attached to handle URIs under /questions.
Related
My express app works fine on the localhost but it does not work on Heroku.
When I added a line it stops working and
the line is
app.use("/api/product", require("./routes/product"))
Here is the code
Index.js
const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
app.get("/", (req, res) => {
res.send("responded")
});
app.use(express.json())
app.use("/api/product", require("./routes/product"))
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
product.js
const express = require("express");
const router = express.Router();
router.get("/", async (req, res) => {
try {
res.json({
status: 200,
message: "Data has been successfully fetched"
});
}
catch (error) {
console.log(error);
return res.status(400).send("server error")
}
})
module.exports = router;
package.json
{
"name": "backend-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.3"
}
}
Folder structure
You would wanna switch your route handlers place. Otherwise you will never rich your api, as the first catches all requests.
const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
app.use(express.json())
app.use("/api/product", require("./routes/product"))
app.get("/", (req, res) => {
res.send("responded")
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
I am attempting to learn express and how to use postman and I'm following along a tutorial. Everything was going well until I tested router.get by sending dummy data to the server. I use postman to attempt to post to my localhost 500. Instead of getting a json back of the data in which I sent, I get a 200 status and nothing at the bottom of my screen. When i check the console upon hitting that route, this is logged to the console: http://undefined/api/members.
Mind you, I have no trouble using router.get to receive a json of all my members and I have no trouble receiving a json by searching with just the member ID. But for whatever reason router.post isn't working for me. I suspect this has to do with the body parser. But I'm not sure why specifically it isn't working. Please help.
This is how I set up my app file:
const express = require('express')
const app = express()
const path = require('path');
const logger = require('./middleware/logger')
const bodyParser = require('body-parser')
app.use(logger)
app.use('/api/members', require('./routes/api/members'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.use(express.static(path.join(__dirname, 'public')))
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${[PORT]}`)
})
The following is how I set up my router file
const express = require('express')
const router = express.Router()
const members = require('../../Members')
router.get('/', (req, res) =>{
res.json(members);
})
router.get('/:id', (req, res) => {
const found = members.some(member => member.id === parseInt(req.params.id));
if(found){
res.json(members.filter(member => member.id === parseInt(req.params.id)))
} else {
res.status(400).json({msg: `No member with the id of ${req.params.id}`})
}
})
router.post('/', (req, res) => {
res.send(req.body)
})
module.exports = router
my package.json:
{
"name": "expressCrashCourse",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index",
"dev": "nodemon index"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"moment": "^2.24.0"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}
Routes are processed in order so if you want the body-parser middleware to be active for your .post() route, the middleware has to be BEFORE it. So, change this:
app.use('/api/members', require('./routes/api/members'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
to this:
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.use('/api/members', require('./routes/api/members')) // <== after your middleware
As it was, it was hitting your route before the middleware got a chance to run and thus req.body was still not populated with the body contents.
I am getting this error when trying to run my code and don't really know how to solve it. I don't really know the codebase because I'm new to it, so I'm completely lost and have no idea what to do.
body-parser deprecated undefined extended: provide extended option index.js:20:20
COMMON_CONFIG.mode === "development" false
Listening on port undefined
edit:
package.json:
**{
"name": "audio-guide-backend",
"version": "0.0.0",
"main": "index.js",
"repository": "https://gitlab.com/islandica/audio-guide-backend.git",
"license": "MIT",
"private": true,
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"dependencies": {
"crypto-random-string": "^3.0.1",
"dotenv": "^8.0.0",
"ejs": "^2.6.2",
"express": "^4.17.1",
"express-session": "^1.16.2",
"pg": "^7.11.0"
},
"devDependencies": {
"nodemon": "^1.19.1"
}
}
**
Edit 2: This is how my index.js looks like:
require("dotenv").config();
const express = require("express");
const http = require("http");
const session = require("express-session");
const bodyParser = require("body-parser");
const { SERVER_CONFIG } = require("./config");
const app = express();
const server = http.createServer(app);
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use((req, res, next) => {
// if (req.url === "/api/login") console.log(req);
next();
});
app.use(express.json());
app.use(bodyParser.urlencoded());
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: true
})
);
// ROUTES
require("./routes")(app);
// NOT FOUND
app.use(function(req, res, next) {
res.status(404);
res.format({
html: function() {
res.render("404");
// res.render("404", { url: req.url });
},
json: function() {
res.json({ message: "Not found" });
},
default: function() {
res.type("txt").send("Not found");
}
});
});
// INTERNAL ERROR
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.format({
html: function() {
res.render("500");
},
json: function() {
res.json({ message: "server error: " + err.message });
},
default: function() {
res.type("txt").send("server error: " + err.message);
}
});
res.send("server error: " + err.message);
/*res.render("500", {
message:
COMMON_CONFIG.mode === "development"
? err.message
: "Internal server error"
});*/
});
server.listen(SERVER_CONFIG.port, err => {
if (err) {
console.log("Error occured");
} else {
console.log(`Listening on port ${SERVER_CONFIG.port}`);
}
});
It looks like my post is mostly code, so I'm adding more details.
Listening on port undefined
This means that you don't have the port set. I see you're using dotenv, so the first place to check is your .env file in the root directory. If one wasn't created, make it and add whatever the name is for the environmental variable referenced in index.js. It's likely PORT.
Next you'll want to review the options you're passing into express.json() or whatever body-parser function you're calling. It's passing an undefined into that also.
Check your .env file or your system environmental variables and add the ones needed.
EDIT:
Check SERVER_CONFIG in the config file. That's where you should have you environmental variables that would usually be in .env. It's possible and likely that SERVER_CONFIG just consumes the dotenv package.
Also, you do not need const server = http.createServer(app); Just replace the call to server.listen(...) with app.listen(...)
Remove bodyParser, and use express.urlencoded({extended: true})
Since the bodyParser is deprecated, I had resolved this issue by setting the extended:true option on the app.
app.use(express.urlencoded({extended: true}));
instead of
app.use(bodyParser.urlencoded());
I want to upload file from postman to node js but I have problem.
POSTMAN
Write url,check post method,check form-data,check file,write file name and choose file
This is my code
app.js
const express = require('express');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
app.use(fileUpload());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
router.js
router.post('/schedule/entry', function(req,res){
console.log(req.file.name);
});
Console return me undefined name, if I write this code
router.post('/schedule/entry', function(req,res){
console.log(req.file);
});
Return 'undefined'
Why?
package.json
{
"name": "nodejs-rest-api-authentication",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.16.1",
"csv-array": "0.0.22",
"csv-write-stream": "^2.0.0",
"express": "^4.14.1",
"express-fileupload": "^0.3.0",
"fast-csv": "^2.4.1",
"formidable": "^1.1.1",
"json2csv": "^3.11.5",
"jsonwebtoken": "^8.1.0",
"mysql": "^2.15.0"
}
}
server.js
const app = require('./app');
const port = process.env.PORT || 3000;
const server = app.listen(port, function() {
console.log('Server listening on port ' + port);
});
screenshots
screenshots
codeGit
Based on the discussion in the comment section:
const express = require('express')
const app = express()
const formidable = require('formidable')
const path = require('path')
const uploadDir = '' // uploading the file to the same path as app.js
app.post('/', (req, res) =>{
var form = new formidable.IncomingForm()
form.multiples = true
form.keepExtensions = true
form.uploadDir = uploadDir
form.parse(req, (err, fields, files) => {
if (err) return res.status(500).json({ error: err })
res.status(200).json({ uploaded: true })
})
form.on('fileBegin', function (name, file) {
const [fileName, fileExt] = file.name.split('.')
file.path = path.join(uploadDir, `${fileName}_${new Date().getTime()}.${fileExt}`)
})
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))
Attached Screenshots:
Because of body-parser middleware file will be not available in req so you must use another middleware libraries like connect-busboy or multer or connect-multiparty
I have recently built an MVC (well, more like a VC app) app in NodeJS and Express. Everything was working fine until I installed express-validator and pasted the middleware in the app file. Afterwards, localhost began hanging, with a GET / - - ms - - message in the console. I started a new app, reinstalled the modules, and copied and pasted the code. I still had the same issue, so I removed the express-validator middleware. Nothing changed.
App.js (entry point):
var config = require('./server/configure');
var express = require('express');
var app = express();
var app = config(app);
app.set('port', process.env.port || 3300);
app.set('views', __dirname + '/views');
app.listen(app.get('port'), function(req, res){
console.log('Server up: http://localhost:' + app.get('port'));
});
The routes file (/server/routes.js)
var express = require('express');
home = require('../controllers/home');
module.exports = function(app) {
router = express.Router();
router.get('/', home.home);
app.use(router);
};
The configure module (/server/configure.js)
var path = require('path'),
routes = require('./routes'),
ejs = require('ejs'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
module.exports = function(app) {
app.use(morgan('dev'));
app.use(bodyParser.json);
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser({
uploadDir: path.join(__dirname, 'public/upload/temp')
}));
app.use(methodOverride());
app.use(cookieParser('secret value'));
routes(app);
app.use('/public/', express.static(path.join(__dirname, '../public')));
if ('development' === app.get('env')) {
app.use(errorHandler());
}
app.set('view engine', 'ejs');
return(app);
};
The home controller (/controllers/home.js):
module.exports = {
home: function(req, res) {
res.render('home');
}
};
The Package file (package.json):
{
"name": "krementcookdev",
"version": "1.0.0",
"description": "the krementcook web application",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Isaac Krementsov",
"license": "ISC",
"dependencies": {
"body-parser": "*",
"cookie-parser": "*",
"ejs": "*",
"errorhandler": "*",
"express": "*",
"express-handlebars": "*",
"express-validator": "*",
"method-override": "*",
"morgan": "*",
"path": "*"
},
"devDependencies": {}
}
Of course, I have a view file (home.ejs) in the /views directory. If you need to see it, let me know and I will add it to the post. Please do not close this a being a duplicate; I have checked similar problems and they mostly regard simple apps without routers or anything like that. I tried the solutions offered that applied to me, but none were relevant or productive.
Update: I did have specific versions in the package file, but I still had the same issue.
Try to use specific version (latest) of individual package in dependencies. for more detail Refer - https://docs.npmjs.com/files/package.json