Node.js Error - Website shows "Cannot GET /" - node.js

When I open the site page it shows Cannot GET /
I tried reading other posts about this problem, but I can't seem to fix this. I am new to this and can not figure this out myself.
require('./config/db');
const app = require('express')();
const port = 3000;
const UserRouter = require('./api/User');
const bodyParser = require('express').json;
app.use(bodyParser());
app.use('/user', UserRouter)
app.listen(port, () => {
console.log(`Server running on port ${port}`);
})

Every route inside UserRouter start with /user
If you did something like this :
var express = require('express');
var router = express.Router();
router.get('/signup', function(req, res) {
/* http://localhost:${port}/user/signup */
});
//Put at the end or will be trigered every time you call a route starting with /user
router.get('*', function(req, res) {
/* http://localhost:${port}/user */
});
signup will be able to access logging inside /User route

Related

Express routes working with url params but not with specific sub routes

I'm building an API for my web app and I was able to successfully send requests to the routes in Post.js when they only had url params. But when I try to create a route like '/allposts' (the last endpoint in Post.js) , I receive a 404 error message on postman. Here's my code:
router.post('/', (req, res) => {
// Endpoint 1 code here
})
router.get('/:id', (req, res) => {
// Endpoint 2 code
})
// This is the route that I can't to send requests to
router.get('/ap', async(req, res) => {
try{
const ap = await P.find()
res.send(ap)
} catch(error){
log(error)
res.status(500).send("error")
}
})
server.js
const express = require('express')
var cors = require('cors')
const fs = require('fs');
const path = require('path');
var app = express()
app.use(express.static(path)
app.use(cors())
const bodyParser = require('body-parser')
app.use(bodyParser.json());
var p = require("./routes/P.js");
app.use('/post', p);
const PORT = process.env.PORT || 3001
app.listen(port, () => {
log(`Listening on port ${PORT}...`)
});
When I send a request to http://localhost:3001/post/ap, I'm getting the a 404 Not Found error, but the first two routes work fine. It seems like routes with url params work, but the allposts route does not. Any help would be greatly appreciated. Thanks.
Main problem is the order of the routes.
router.get('/:id') will be initialized before router.get('/allposts'). So when you want to access /allposts the first router will catch it.
You need to switch the init order.
First router.get('/allposts') then router.get('/:id').

why does express middleware not working in separate files

I want to broke down my routers into separate file rather than keeping all API routes in a single file. So i tried to identify user URL using a middle ware and call the api according to the url as you seeing bellow but middleware function is not working . how to solve this?
//HERE IS INDEX.jS file CODE
const express = require("express");
const dotenv = require("dotenv");
const app = express();
const PORT = process.env.PORT || 7000;
app.listen(PORT);
app.use("/users", require("./routes/users/users"));
//==========================================================
//HERE IS users.js FILE CODE
const express = require("express");`enter code here`
const router = require("express").Router();
express().use(selectApi);
function selectApi(req, res, next) {
console.log("this line also not executing")
switch(req.originalUrl){
case '/':
// calling api here from a nother separate file
case '/user/:id'
// calling api here from a nother separate file
}
}
module.exports = router;
There is an example in the Express.js Routing Guide. I've modified it slightly to fit your example.
users.js
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
// calling api here from a nother separate file
})
router.get('/user/:id', function (req, res) {
// calling api here from a nother separate file
})
module.exports = router
index.js
const express = require("express");
const dotenv = require("dotenv");
const app = express();
const PORT = process.env.PORT || 7000;
app.listen(PORT);
app.use("/users", require("./routes/users/users"));

node express returns "Cannot Get" other solutions/ code not working. file upload

tldr
Ok i've been trying to get a file upload server working for a few days now and evrything i try just returns cannot get.
i'm currently trying the setup below but it is not working
code
here is server.js
const express = require("express");
const upload = require("./upload");
const cors = require("cors");
var router = express.Router();
var app = express();
const server = express();
var corsOptions = {
origin: "*",
optionsSuccessStatus: 200
};
server.use(cors(corsOptions));
router.get("/", function(req, res) {
res.render("index", { title: "Express" });
});
server.post("/upload", upload);
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`listening on port ${port}`);
});
Below is upload.js
const IncomingForm = require("formidable").IncomingForm;
module.exports = function upload(req, res) { var form = new IncomingForm();
form.on("file", (field, file) => {
// Do something with the file
// e.g. save it to the database
// you can access it using file.path
console.log("thisno werk"); }); form.on("end", () => {
res.json(); }); form.parse(req); };
Let's mean server as the result of the const server = require('express')();, and router as the result of const router = require('express').Router();.
server is an instance of your Express server while router is an instance of API endpoints router. You don't only need to write your router router.get();, but you also need to set the appropriate files (so-called controllers) for handling API requests.
So your code should have this line: server.use('/', yourController); or simply server.get('/', handlingFunction); if you don't have API sections.
However, if you use routers, then you need the first variant.
Your POST /upload method works great because it's configured on the app level. But you need to fix your GET / method because it's configured on the router level that is unused in your app.
Source: Express routing

Rest Api with node.js localhost not answering

Hy there, I'm trying to learn to make a REST API. I have the following code, where I mention that i have no error. When I try to access localhost:3000 nothing happens it's just reloading a blank page. What am I doing wrong?
Servers.js
const http = require('http');
const app = require('./app').default;
const port = process.env.port || 3000;
const server = http.createServer();
server.listen(port);
App.js
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.status(200).json({
message: 'It works!'
});
});
module.exports = app;
You've not defined any route. Express generator generates the boilerplate code which is use full to start with.
You can also define a route like this:
app.use('/', function (req, res, next) {
return res.render('index', {title: 'DASHBOARD', 'data': ''});
});
Have a look at this doc: https://expressjs.com/en/starter/generator.html

Express router basic usage resulting in 404

I am trying to build my express app to have routes within routes as shown below and I am getting a 404 error.
What I am trying to do is simply, route all traffic with api in the route to the routes/api.js file, then from there, based on the end of the url, depending on if its signup or login, route to the corresponding signup.js or login.js file.
Note, moving the code from routes/signup.js to routes/app.js works perfectly fine.
Has anyone gotten unexpected 404 errors under a similar set up? I appreciate any suggestions on how to resolve.
server/index.js
import express from 'express';
const app = express();
app.use('/api', require('./routes/api'));
app.use('*', (req,res) => {
res.status(404).send('404: Not Found');
});
app.listen(3000, function() {
console.log('api is running on port 3000');
});
server/routes/api.js
var express = require("express");
var router = express.Router();
router.use('/signup', require('./signup'));
router.use('/login', require('./login'));
module.exports = router;
server/routes/signup.js
var express = require("express");
var router = express.Router();
router.post('/api/signup', (req, res) => {
res.send('HELLO WORLD');
});
module.exports = router;

Resources