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.
Related
EDIT: To be clear, this only happening when i'm trying to host the app. Works PERFECT during local environment testing..
When trying to fetch data from my backend getting an error in Chrome saying that JS is not enabled. (IT IS) so that is not the issue..
Thinking there may be an issue with my package.json maybe if the commands are incorrect for use on the host machine? Have tried Render & Heroku same issues.
I had tried to run the commands within my local environment and the app works flawlessly fetching data as intended. Only when hosting the app do I not get any data back from the server when making API call from the front end, instead get JS not enabled error in the Network tab and no errors on Front End that I can see..
Hosted app to see network error: https://elf-invasion.herokuapp.com/
File Structure:
/root
|- config.js
|- server.js
|- package.json + package-lock.json
|- client/
|- vue.config.json
|- ... (rest of dist, src, node_modules, public etc.)
|- models/
|- Elf.js + HighScore.js
|- routes/
|- api/
|- elf.js + highScore.js
config.js
module.exports = {
hostUrl: process.env.HOST_URL,
mongoURI: process.env.MONGO_URI,
PORT: process.env.PORT || 3000,
};
server.js
const express = require("express");
const app = express();
const port = 3000;
const mongoose = require("mongoose");
const { PORT, mongoURI } = require("./config.js");
// routes
const Player = require("./routes/api/player");
const Elf = require("./routes/api/elf");
const HighScore = require("./routes/api/highScore");
// cors is a middleware that allows us to make requests from our frontend to our backend
const cors = require("cors");
// morgan is a middleware that logs all requests to the console
const morgan = require("morgan");
// body-parser is a middleware that allows us to access the body of a request
const bodyParser = require("body-parser");
const path = require("path");
app.use(cors());
// use tiny to log only the request method and the status code
app.use(morgan("tiny"));
app.use(bodyParser.json());
// chek if we are in production
if (process.env.NODE_ENV === "production") {
// check if we are in production mode
app.use(express.static("client/dist"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "dist", "index.html"));
});
}
// test if server is running and connected to mongoDB
app.get("/", (req, res) => {
res.send("Hello World!");
});
// app.get("/", (req, res) => {
// res.send("Hello World!");
// });
// use routes
app.use("/api/", Player);
app.use("/api/", Elf);
app.use("/api/", HighScore);
mongoose
.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB connected..."))
.then(() => {
// log uri to console
console.log(`MongoDB connected to ${mongoURI}`);
})
.catch((err) => console.log(err));
app.listen(PORT, () => {
console.log(`Example app listening at ${PORT}`);
});
package.json
{
"name": "week1",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"server": "nodemon server.js --ignore 'client/'",
"client": "npm run serve --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"start": "node server.js",
"build": "npm install --prefix client && npm run build --prefix client"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"bootstrap": "^5.2.3",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"mongoose": "^6.7.5",
"morgan": "^1.10.0",
"portal-vue": "^2.1.7"
},
"devDependencies": {
"concurrently": "^7.6.0",
"nodemon": "^2.0.20"
}
}
I want to use bodyParser on express. My posts.js file has
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
router.post('/', (req, res) => {
console.log(req.body);
});
module.exports = router;
On app.js file, the code is like
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const postsRoutes = require('./routes/posts');
// const usersRoutes = require('./routes/users');
app.use('/posts', postsRoutes);
// app.use('/users', usersRoutes);
Dependencies versions are
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.9.7",
"nodemon": "^2.0.3"
Server connected successfully but when I pass the data through postman on json mode, the terminal shows error like
SyntaxError: Unexpected token t in JSON at position 3
at JSON.parse (<anonymous>)...
I used the following code on app.js
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
because now express has buiild-in body-person function but output same here.
What can I do to solve this problem? I need help. Thanks in advance!
In JSON keys must be strings, try the following in the postman payload:
{
"title": "Title here",
"Description": "Description here..."
}
Instead of this:
{
title: "Title here",
Description: "Description here..."
}
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'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.