I'm attempting to access a route directly from a request, even though another subfolder works the other does not. Repeatedly throwing 404 errors. /api/getPostList works but /post/ or /post/:title doesn't work.
I've restructured the code, attempted to change it from a get request to a post request, added /post/:title to access an individual post or without a / to access the main list.
Server.js contains
app.use('/', Routes);
routes/index.js contains
const router = require('express').Router();
const posts = require('./posts');
const api = require('./api');
router.use('/post', posts);
router.use('/api', api);
module.exports = router;
routes/api/index.js contains
Api.get('/getPostList', (req, res) => {
PostModel.find(function (err, post) {
if (err) return console.log('error: ' + err);
return res.json({ postList: post});
});
console.log("Attempted to get post list on /getPost/ route: " + ++postRouteCnt);
});
Api.get('/getPost/:title', getPost);
module.exports = Api;
routes/post/index.js contains
const Posts = require('express').Router();
const post = require('./post');
const PostModel = require('../../../server/models.js');
let postRouteCnt = 0;
Posts.get('/', (req, res) => {
PostModel.find(function (err, post) {
if (err) return console.log('error: ' + err);
return res.json({ postList: post});
});
console.log("Attempted to get post list on /post/ route: " + ++postRouteCnt);
});
Posts.get('/:title', post);
module.exports = Posts;
When calling /post/ I get a 404 Cannot GET /post/ when I should receive the json response.
EDIT:
Folder structure
Server/
routes/
api/
index.js
getPost.js (for individual post)
posts/
index.js
post.js (for individual post)
server.js
Base on your structure folder, I try to write code with simple code
App.js :
const express = require('express')
const app = express()
const port = 3000
const Routes = require('./routes/posts/index.js');
app.use('/', Routes);
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
.routes/ posts/ index.js :
const express = require('express');
const router = express.Router();
const postController = require('./post');
// GET /
router.get('/posts', postController.getPosts);
module.exports = router;
.routes/ posts/ post.js :
exports.getPosts = (req,res) => {
res.send('test');
}
Try input http://localhost:3000/posts and its work
You can write any logic in .routes/ posts/ post.js :
try changing it like this
Posts.get('/', (req, res) => {
PostModel.find(function (err, post) {
if (err) throw err;
res.send({ postList: post});
});
console.log("Attempted to get post list on /post/ route: " + ++postRouteCnt);
});
now try this url
/post/
Related
This is my Express code by using handlebars using .hbs code
const express = require("express");
const path = require("path");
const app = express();
const port = 3001;
//for mongo all mongodata
require("dotenv").config();
const cors = require("cors");
app.use(cors());
const Handle = require("./views/mongoschema");
const staticPath= path.join(__dirname, "./views");
app.set("view engine","hbs");
app.use(express.static(staticPath));
//for maintaining the format
app.use(express.json());
//to GET the data in the from the form
app.use(express.urlencoded({extended:false}));
//to render the page this is coming (1st)
app.get("/",(req, res) => {
res.render('index');
});
//for login validation
app.post("/mongoschema",async(req, res) => {
try {
const handleData = new Handle({
title: req.body.one,
description: req.body.two,
url: req.body.four
})
const handled = await handleData.save();
//After REGISTRATION sending the user to index file
***res.status(201).render("index");***
} catch (error) {
res.status(400).send(error);
}
});
app.get("/pages", (req, res) => {
Handle.find({})
.then((items) => res.json(items))
.catch((err) => console.log(err));
});
app.listen(port, () => {
console.log('listening to the port ${port)');
});
the file i want to run now is a "file.js" and index is "index.hbs" it is not able to render the "file.js" how can i render or i will be redirected to the "file.js" file After when my login is SUCCESSFUL.
As someone mentioned in the comments, you should be using:
res.redirect("/"); // path to route as parameter - in this case, index.
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var port = 3000;
const fs = require('fs');
// we are connecting to the mangodb using mangoose
var mongoose = require("mongoose");
// Now we are using bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true })
// now we are creating the schema to the database
var nameSchema = new mongoose.Schema({
firstName: String,
lastNameName: String
});
// Now we have to create a model
var User = mongoose.model("User", nameSchema);
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
// Now we are posting the data
app.post("/addname", (req, res) => {
console.log("nnnnnn")
console.log(req.body.firstName)
var myData = new User(req.body);
myData.save()
console.log(myData);
fs.writeFile(__dirname +"/data.json",myData, function(err){
if(err) {
return console.log(err);
}
console.log("The file is saved ");
})
console.log(myData)
})
// Now we are getting the data
app.listen(port, () => {
console.log("Server listening on port " + port);
});
1)I am using express app.post to post the data into database and store the data into the write file to check
2) app.post is not working it tried console.log to check but it is not going inside the function
3) I am not getting output as well as any error plese help me
there is no error handling and response handling in this code.
it will be readable if we write post method with async/await :
app.post("/addname", async (req, res) => {
console.log("nnnnnn")
console.log(req.body.firstName)
var myData = new User(req.body);
await myData.save()
console.log(myData);
fs.writeFileSync(__dirname +"/data.json", myData)
console.log(myData)
})
you will add next() to app.use
var User = mongoose.model("User", nameSchema);
app.use("/", (req, res,next) => {
res.sendFile(__dirname + "/index.html");
next()
});
// Now we are posting the data
app.post("/addname", (req, res) => {
console.log("nnnnnn")
console.log(req.body.firstName)
var myData = new User(req.body);
myData.save()
console.log(myData);
fs.writeFile(__dirname +"/data.json",myData, function(err){
if(err) {
return console.log(err);
}
console.log("The file is saved ");
})
console.log(myData)
})
// Now we are getting the data
app.listen(port, () => {
console.log("Server listening on port " + port);
});
That's because every request is going to this app.use code block. app.use("/", (req, res) => { ... });
Just Put it below the app.post("/addname", (req, res) => { ... });
app.use is used to mount middlewares into the request-response chain. So, every request that comes matches the /(which is essentially every request) goes inside that middleware. So, use your routes first then use the middleware at the end.
EDIT:
Let me give you a mcve which I tested locally:
const express = require('express');
const fakeData = function(){
return {
s: "fakeData"
}
}
const app = express();
const port = 8181
const path = require('path')
app.get("/a", (req, res) => {
return res.json({d:'yay'});
});
app.use('/',(req,res)=>{
return res.json(fakeData());
})
app.listen(port, () => {
console.log(`Server started on PORT ${port}`);
});
Because every request goes through a mounted middleware, so when you GET/POST/ANYTHING to localhost:8181/<abosulutely_any_path> it will go through the app.use because it treats that function as middleware and will return { s: "fakeData" }.
But when you make a GET call http://localhost:8181/a it will go to the app.get route BECAUSE WE DECLARED IT FIRST and return { d : "yay" }
I am using express backend with a react frontend everything is working fine but occasionally i get error
Cant set header after they are sent
and server gets down.i searched few ways this error might happen but in my code i could not find such cases.i tried to be simple as possible in the code.can anyone please point me what might be the issue?
Server.js file
// call the packages we need
const addItem = require('./controllers/addItem');
const addCategory = require('./controllers/addCategory');
const addSubCategory = require('./controllers/addSubCategory');
const getSubCategory = require('./controllers/getSubCategoryByCategory');
const getCategory = require('./controllers/getAllCategory');
const getAllItems = require('./controllers/getAllItems');
const cors = require('cors');
const express = require('express');
// call express
const app = express(); // define our app using express
const bodyParser = require('body-parser');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
const port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
const addItemRoute = express.Router(); // get an instance of the express Router
const getCategoryRoute = express.Router();
const addCategoryRoute = express.Router();
const addSubCategoryRoute = express.Router();
const getSubCategoryRoute = express.Router();
const getAllItemsRoute = express.Router();
getCategoryRoute.get('/get_category', (req, res) => {
getCategory(res);
});
addCategoryRoute.post('/add_category', (req, res) => {
addCategory(req.body.name, res);
});
getSubCategoryRoute.get('/get_subcategory/:catId', (req, res) => {
getSubCategory(req.params.catId, res);
});
addSubCategoryRoute.post('/add_subcategory', (req, res) => {
addSubCategory(req.body.name, req.body.cat_id, res);
});
// code, name, quantity, length, description and subcategory id should be passed as parameters
addItemRoute.post('/add_item', (req, res) => {
addItem(req.body.item, res);
});
getAllItemsRoute.get('/get_items', (req, res) => {
getAllItems(res);
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', addItemRoute);
app.use('/api', getCategoryRoute);
app.use('/api', addCategoryRoute);
app.use('/api', addSubCategoryRoute);
app.use('/api', getSubCategoryRoute);
app.use('/api', getAllItemsRoute);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log(`Server started on port ${port}`);
getAllCategories() function
Object.defineProperty(exports, '__esModule', {
value: true,
});
const pool = require('./connection');
module.exports = function (res) {
pool.getConnection((err, connection) => {
if (err) {
connection.release();
return res.json({ code: 100, status: 'Error in connection database' });
}
console.log(`connected as id ${connection.threadId}`);
connection.query('select * from category;', (err, rows) => {
connection.release();
if (!err) {
return res.json(rows);
}
});
connection.on('error', err => res.json({ code: 100, status: 'Error in connection database' }));
});
};
If you get an error in connection.query() you send a response with res.json(). This error is caught in connection.on('error') where you send another response. You can't send two responses to the same request. It seems that in this case, you don't really need connection.on() at all or if you have it to catch other errors, don't send a response on connection.query()'s error.
I am trying to connect my Angular2 to my nodeJs server. I have an authentication form which makes a post request. And I would like to use node to handle the post request.
But so far I am unable to make my post request working. The console.log doesn't display anything.
What I am missing?
This is my server.js which points to the folder dist in which i made the build of angular.
const express = require('express');
const path = require('path');
const http = require('http');
var walker = require('node-sync-walker');
const bodyParser = require('body-parser');
// Get our API routes
const api = require('./server/routes/api');
var app = express();
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Set our api routes
app.use('/api', api);
// Catch all other routes and return the index file
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
walker.routeWalker(__dirname + '/server/routes', app);
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3000';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on localhost:${port}`));
This is my api.js
var users = [{username: "user", password: "password"}];
var router = require('express').Router();
module.exports = function(app) {
router.post('/api/authenticate',
function(req, res) {
console.log("print something");
let params = JSON.parse(req.body);
// find if any user matches login credentials
let filteredUsers = users.filter(user => {
return user.username === params.username && user.password === params.password;
});
if (filteredUsers.length) {
res.sendStatus(200);
} else {
console.log("print something else");
return res.sendStatus(400)
}
//return;
});
}
You are configuring the route as '/api/api/authenticate'
You should remove '/api' from routes in api.js
Finally, it worked! I removed the api in /api/authenticate as #catalacs suggested. Then I changed how I import the module router from api.js to server.js.
server.js
var users = [{username: "test", password: "test"}];
var router = require('express').Router();
router.post('/authenticate',
function(req, res) {
console.log("print something");
let params = JSON.parse(req.body);
// find if any user matches login credentials
let filteredUsers = users.filter(user => {
return user.username === params.username && user.password === params.password;
});
if (filteredUsers.length) {
res.sendStatus(200);
} else {
console.log("print something else");
return res.sendStatus(400)
}
//return;
});
module.exports = router;
And in my server.js, I commented out this line:
walker.routeWalker(__dirname + '/server/routes', router);
I am building an API backend with Express (v4) and facing an issue that my middleware function is not called
on sub-paths of my route. E.g. it is called for /movie but not for /movie/search.
I have split my routes into separate files. Below is the code, shortened to the relevant parts.
Any help is appreciated!
app.js
var express = require('express');
var app = express();
var router = require('routes')(app);
/routes/index.js
module.exports = function(app) {
app.use('/movie', check_authentication, require('movie'));
};
/routes/movie.js
var Movie = require(../models/movie');
// Middleware is working for this route (/movie?movie_id=123)
router.get('/', function(req, res) {
Movie.findById(req.query.movie_id)
.then(function(movie) {
res.status(200).json(movie);
}, function(err) {
res.status(400).send(err);
});
});
// Middleware is NOT working for this route (/movie/search?keyword=matrix)
router.get('/search', function(req, res) {
Movie.findById(req.query.keyword)
.then(function(movie) {
res.status(200).json(movie);
}, function(err) {
res.status(400).send(err);
});
});
/routes/check_authentication.js
var express = require('express');
var router = express.Router();
var firebaseAdmin = require('firebase-admin');
var path = require('path');
var config = require(path.resolve(__dirname, '../config/config.json'));
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(path.resolve(__dirname, '../config/' + config.firebase.serviceAccount)),
databaseURL: config.firebase.databaseURL
});
// AUTHENTICATION MIDDLEWARE
// needs to be included in any request which requires authorization
// =============================================================================
router.all('/', function(req, res, next) {
// check if authorization header is present
var token = req.headers['authorization'];
if (typeof token === 'undefined') {
res.status(403).json({ Error: 'Unauthenticated' });
}
else {
firebaseAdmin.auth().verifyIdToken(token).then(function(decodedToken) {
req.email = decodedToken.email;
next(); // all good. go ahead with the request
}).catch(function(error) {
res.status(403).json({ Error: 'Unauthenticated' });
});
}
});
module.exports = router;
It seems I found the problem.
Changing the middleware to trigger on * fixes it.
router.all('*', function(req, res, next)
Maybe someone can confirm that this is the way to go.
The check_authentication module should export the middleware function, not a router.
module.exports = function(req, res, next) {
// check if authorization header is present
// ...
});