I'm getting a Cannot GET error when I try express routing with parameters for the first time and I don't know why.
It worked fine and I installed lodash and now nothing works anymore.
Here`s the code:
app.get("/posts/:postName"), function (req, res) {
let requestedTitle = req.params.postName;
posts.forEach(function(post) {
let storedTitle = post.title;
if (storedTitle === requestedTitle) {
console.log('match found');
} else {
console.log('no match found');
}
});
};
I'm using Localhost and when I try to run it it gives me a Cannot Get error.
For example I enter: http://localhost:3000/posts/test
And usually it kept me on the home route and console logged if it matched one of my entries before or not.
I have Express installed and everything heres the complete code. But it just won't work anymore after installing lodash, do you guys see an error somewhere here? I'm staring at this for 3 days now lol:
//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const _ = require('lodash');
const homeStartingContent = "text";
const app = express();
let posts = [];
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.get("/", function(req, res) {
res.render(__dirname + "/views/home.ejs", {homeStartingContent: homeStartingContent, posts: posts});
});
app.get('/about', (req, res) => {
res.render('about', {aboutContent: aboutContent});
});
app.get('/contact', (req, res) => {
res.render('contact', {contactContent: contactContent});
});
app.get('/compose', (req, res) => {
res.render('compose');
});
app.post('/compose', (req, res) => {
posts.push(req.body);
console.log(posts)
res.redirect('/')
});
app.get("/posts/:postName"), function (req, res) {
let requestedTitle = req.params.postName;
posts.forEach(function(post) {
let storedTitle = post.title;
if (storedTitle === requestedTitle) {
console.log('match found');
} else {
console.log('no match found');
}
});
};
app.listen(3000, function() {
console.log("Server started on port 3000");
});
In the Express documentation it showed this code example and I feel my code should definitely work. I don't understand why it is not.
app.get('/users/:userId/books/:bookId', (req, res) => {
res.send(req.params)
})
Notice the closing parentheses:
app.get("/posts/:postName"), function (req, res) {
^
It shouldn't be there, but at the end of the handler function.
Related
When i try t run this code, i don't get any error but i get a blank screen when i open loclhost.
const path = require("path")
const express = require("express")
app = express()
app.get("/", (req, res) => {
let fullpath = path.join(__dirname, './index.html')
console.log(fullpath)
res.sendFile(fullpath)
console.log("File sent")
res.end()
})
app.listen(5500, () => {
console.log("Server started")
})
Im using linux, express version is 4.18.2, node version is 18.1.0
I executed the same code in a windows machine with same express version and it worked without any error. Maybe its something to do with linux compatibility or maybe how paths are different in windows and linux.
Things i have tried so far:
const path = require("path")
const express = require("express")
app = express()
app.get("/", (req, res) => {
let fullpath = path.join(__dirname, './index.html')
res.sendFile(fullpath, { root: '/' })
console.log("File sent")
res.end()
})
app.listen(5500, () => {
console.log("Server started")
})
const path = require("path")
const express = require("express")
app = express()
app.get("/", (req, res) => {
var options = {
root: path.join(__dirname)
}
let fileName = 'index.html'
res.sendFile(fileName, options)
console.log("File sent")
res.end()
})
app.listen(5500, () => {
console.log("Server started")
})
Simple Answer:
Remove res.end();
Try this code
const express = require("express")
app = express()
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html")
console.log("File sent")
})
app.listen(5500, () => {
console.log("Server started")
})
I am trying to create a login page and sign up page, my app.js gives me this error, I think it is the last line of this code. I can send you the other components(files) for this express app. I cannot understand what is causing this error.
const express = require('express');
const mongoose = require('mongoose');
// Routes
const authRoutes = require('./routes/authRoutes');
const app = express();
// middleware
app.use(express.static('public'));
app.use((err, req, res, next) => {
res.locals.error = err;
res.status(err.status);
res.render('error');
});
// view engine
app.set('view engine', 'ejs');
// database connection
const dbURI = '<database, username and password>';
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true })
.then((result) => app.listen(3000))
.catch((err) => console.log(err));
// routes
app.get('/', (req, res) => res.render('home'));
app.get('/smoothies', (req, res) => res.render('smoothies'));
app.use(authRoutes);
authRoutes.js
const { Router } = require('express')
const authController = require('./authController.js')
const router = Router();
router.get('/signup', authController.signup_get);
router.get('/signup', authController.signup_post);
router.get('/login', authController.login_get);
router.get('/login', authController.login_post);
module.export = router;
authController.js
module.exports.signup_get = (req, res) => {
res.render('signup');
}
module.exports.login_get = (req, res) => {
res.render('login');
}
module.exports.signup_post = (req, res) => {
res.send('signup');
}
module.exports.login_post = (req, res) => {
res.send('login');
}
You are exporting incorrectly in authRoutes.js.
Change this:
module.export = router;
to this:
module.exports = router;
FYI, a little debugging on your own by simply doing a console.log(authRoutes) should have been able to show you where to look for the problem. If you get an error when you attempt to use authRoutes, you look at what it is and where it came from to see why it's not working. This is basic debugging and there is an expectation that you've done basic debugging before you post your question here.
On the client side, I have an application based on threejs an d javascript. I want to send data to the server written in express using fetch. Unfortunately, the server does not receive the data and the browser also gives an error:
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
Application:
this.username = prompt("Username:");
const body = JSON.stringify({ username: this.username });
fetch("http://localhost:3000/addUser", { method: "POST", body })
.then((response) => response.json())
.then(
(data) => (
console.log(data), (this.aktualny_album_piosenki = data.files)
)
);
Server:
var express = require("express")
var app = express()
const PORT = 3000;
var path = require("path");
app.use(express.static('dist'));
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var cors = require('cors');
app.use(cors());
app.post("/addUser", function (req, res) {
console.log(req.body)
})
I might be wrong but maybe try... (very bottom of your main server file)
app.listen((PORT) => {
console.log(`app is listening on port ${PORT}`);
})
is required maybe? I have this chunk of code in every project of my own so maybe that could fix the server not recognizing the api request
express documentation on app listen
heres what I use typically... this is a boilerplate for every one of my projects
const express = require("express");
const app = express();
const connectDB = require("./config/db.js");
const router = express.Router();
const config = require("config");
// init middleware
const bodyParser = require('body-parser');
const cors = require("cors");
const mongoDB = require("./config/db.js");
const path = require("path");
const http = require("http");
const server = http.createServer(app);
const io = require('socket.io')(server, {
cors: {
origin: '*',
}
});
const xss = require('xss-clean');
const helmet = require("helmet");
const mongoSanitize = require('express-mongo-sanitize');
const rateLimit = require("express-rate-limit");
const PORT = process.env.PORT || 5000;
mongoDB();
app.options('*', cors());
app.use('*', cors());
app.use(cors());
const limitSize = (fn) => {
return (req, res, next) => {
if (req.path === '/upload/profile/pic/video') {
fn(req, res, next);
} else {
next();
}
}
}
const limiter = rateLimit({
max: 100,// max requests
windowMs: 60 * 60 * 1000 * 1000, // remove the last 1000 for production
message: 'Too many requests' // message to send
});
app.use(xss());
app.use(helmet());
app.use(mongoSanitize());
app.use(limiter);
// app.use routes go here... e.g. app.use("/login", require("./routes/file.js");
app.get('*', function(req, res) {
res.sendFile(__dirname, './client/public/index.html')
})
app.get('*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
};
};
});
app.get('/*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
};
};
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
if (process.env.NODE_ENV === "production") {
// Express will serve up production files
app.use(express.static("client/build"));
// serve up index.html file if it doenst recognize the route
app.get('*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
}
})
app.get('/*', cors(), function(_, res) {
res.sendFile(path.join(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
};
io.on("connection", socket => {
console.log("New client connected");
socket.on("disconnect", () => console.log("Client disconnected"));
});
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}!`);
});
client-side fetch request looks good to me its prob a server/express.JS thing but like i said i may be wrong but worth trying
I can't get my data, Post function is working fine I'm using Postman for testing it. When I put localhost:3000/api/names/2, I get this error
Can not GET /api/names/2
const express = require('express');
const app = express();
var cors =require('cors')
app.use(express.json()); app.use(cors())
const names = []
app.get('/api/names/', (req, res) => {
res.send(names);
} );
app.post('/api/names', (req, res) => {
const name = {
id: names.length,
name :req.body.name
};
names.push(name);
res.send(name);
});
app.listen(3000, () => console.log('port 3000'));
To GET
app.get('/api/names/:id', (req, res) => { res.send(names.filter(x => x.id == req.params.id););
I did a simple modularization through Node.js.
And I tried to do an api test through Postman, but my nodemon says that the following error occurred.
error
Error: Route.post() requires a callback function but got a [object Undefined]
at Route.
routes/router.js
const express = require('express');
const route = express.Router();
const user = require('../controller/user');
route.route('/user')
.post(user.createUser)
.get(user.readUser)
.put(user.updateUser)
.delete(user.deleteUser)
module.exports = route;
controller/user.js
exports.createUser = function (req, res) {
res.send('user create.')
}
exports.readUser = function (req, res) {
res.send('user read.')
}
exports.updateUser = function (req, res) {
res.send('user update.')
}
exports.deleteUser = function (req, res) {
res.send('user delete.')
}
server.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const router = require('./routes/router');
app.use(router);
app.listen(port, err => {
if(err) console.log(err)
else console.log('server on');
});
What's wrong with me?
I would suggest transforming your current code (controller/user.js) to:
module.exports = {
createUser: function(req, res){
res.send('User created')
},
readUser: function (req, res) {
res.send('Viewing user.')
},
updateUser: function (req, res) {
res.send('User updated.')
},
deleteUser: function (req, res) {
res.send('User deleted.')
}}