I'm trying to build a demo application and having "Cannot GET /" error when I try to reach out http://localhost:8800/
On the other hand, the output as expected:
Connected to backend.
mongoDB connected!
Connected to mongoDB.
So I couldn't understand where exactly I have the problem, do you have any suggestions?
import mongoose from "mongoose";
import express from "express";
import authRoute from "./routes/auth.js";
import usersRoute from "./routes/users.js";
import hotelsRoute from "./routes/hotels.js";
import roomsRoute from "./routes/rooms.js";
const app = express();
// dotenv.config()
const connect = async ()=>{
try {
await mongoose.connect('mongodb+srv://********#******.mongodb.net/?retryWrites=true&w=majority');
// Check how we can use .env file
console.log("Connected to mongoDB.")
} catch (error) {
throw error
}
};
mongoose.connection.on("disconnected", ()=>{
console.log("mongoDB disconnected!")
})
mongoose.connection.on("connected", ()=>{
console.log("mongoDB connected!")
})
app.use(express.json())
app.use("api/auth", authRoute);
app.use("api/users", usersRoute);
app.use("api/hotels", hotelsRoute);
app.use("api/rooms", roomsRoute);
app.listen(8800, ()=>{
connect()
console.log("Connected to backend.")
});
auth.js
import express from "express";
const router = express.Router();
router.get("/auth", (req,res)=>{
res.send("Hello, this is auth endpoint");
})
router.get("/register", (req,res)=>{
res.send("Hello, this is auth register endpoint");
})
export default router
You don't need a root route. However, if you still want something to display, you can just add in your code :
app.get('/', (_, res) => res.send({message: 'Hello from Express'}))
Your code is running, it just doesn't have a route at '/', which is your path when you go to any website. if you want to render something on the page, just add
app.get('/', (req, res)=>{
res.send('this text will now appear at localhost:8800');
/*
you could also import path and do
path.join(__dirname+'yourfilename.html') to render an html file
*/
})
you can make '/' root
app.get('/', (req, res) => {
res.send('Hello World!')
})
Related
I have three files when I try running index.js file DB work well but router does not work and if run server.js DB and router does not work
server
import express from 'express'
import cors from 'cors'
import restaurants from './api/restaurants.route.js'
const app = express()
app.use(cors())
app.use(express.json())
app.use("/api/v1/restaurants", restaurants)
app.use("*", (req, res) => res.status(404).json({error: "Not Found"})) // any router not found in our routers
export default app;
index
import app from './server.js'
import mongodb from 'mongodb'
import dotenv from 'dotenv'
dotenv.config()
const mongoClient = mongodb.MongoClient
const port = process.env.PORT || 8000
mongoClient.connect(
process.env.RESTREVIEWS_DB_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
).catch((e) => {
console.log(e.stack)
process.exit(1)
}).then(async client => {
app.listen(port, () => {
console.log(`app listen in link http://localhost:${port}/api/v1/restaurants`)
})
})
router
import express from 'express'
const router = express.Router();
router.get('/api/v1/restaurants', (req, res) => {
res.status(200).send("HelloWorld");
})
export default router
I'm using node.js to build a REST CRUD, and to check if my urls are working i'm trying to get a "Hello1" message when I acess the url "localhost:5000/users", but all I get when I acess it is Cannot GET /users. I really don't know what's wrong with my code, because i'm following exactly what the tutorial says. Does anybody know what's going on?
users.js file:
import express from 'express';
const router = express.Router();
router.get('/' , (req,res) => {
res.send("Hello1");
});
export default router;
//////////////////////////////////////
index.js file
import express from 'express';
import bodyParser from 'body-parser';
import usersRoutes from './routes/users.js';
const app = express();
const PORT = 5000;
app.use(bodyParser.json());
app.get('/', (req,res) => {
res.send("hello");
})
app.get('/users', usersRoutes);
app.listen(PORT, () => console.log("Server running on localhost:"+PORT));
Instead of:
app.get('/users', usersRoutes);
You should use:
app.use('/users', usersRoutes);
I'm facing some issues with my express server when I use the 'app.use' command
in my task-routes.js file, I have the following code
import express from 'express';
const router = express.Router();
router.post('/task',(req, res) => {
res.send('post.task - create a task');
});
router.get('/task',(req, res) => {
res.send('get.task - get all tasks')
});
router.get('/task/:id',(req, res) => {
res.send('get.task/:id - get task by id')
});
router.put('/task',(req, res) => {
res.send('put.task - update a task')
});
router.delete('/task',(req, res) => {
res.send('delete.task - delete a task')
});
export default router;
And in my routes.js file, I have this
import taskRoutes from './api/task/tasks-routes';
export function registerRoutes(app) {
app.use('/api',taskRoutes);
}
Index.js
import express from 'express';
const app = express()
import {registerRoutes} from './routes';
const port = 3000
registerRoutes();
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`MEVN app listening at http://localhost:${port}`))
This is the error I keep getting
/Users/musabhamid/Desktop/mevn-stack copy/prod-server/routes.js:15
app.use('/api', _tasksRoutes2.default);
^
TypeError: Cannot read property 'use' of undefined
at registerRoutes (/Users/musabhamid/Desktop/mevn-stack copy/prod-server/routes.js:15:7)
at Object.<anonymous> (/Users/musabhamid/Desktop/mevn-stack copy/prod-server/index.js:14:28)
You are missing to pass app as argument at Index.js
import express from 'express';
const app = express()
import {registerRoutes} from './routes';
const port = 3000
registerRoutes(app); // <- Here
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`MEVN app listening at http://localhost:${port}`))
app.use('/api',taskRoutes);
So you call app.use
What is app?
export function registerRoutes(app) {
It is the first argument you pass to registerRoutes.
So what is that?
registerRoutes();
There isn't one. You didn't pass it an argument.
You have to pass the express object as the argument when you call the function.
I am trying to build a basic Express api and am running in to an odd module not found error. Before introducing TypeScript to my project, I never got this error. This has been quite frustrating to resolve. I appreciate any suggestions on why I am getting this error and how to resolve.
server.ts
import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
//import * as api from "api"; also tried this
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use('/api', require('./api'));
app.use('*', (req, res, next) => {
let error = new Error('404: not found');
next(error);
});
app.use((error, req, res, next) => {
res.status(500).send({
error: {
message: error.message
}
});
});
const port = 3000;
app.listen(port, () => {
console.log('listening on port', port);
});
module.exports = app;
api/api.ts
import express from "express";
const router = express.Router();
router.use('/', (req, res, next) => {
res.send('cool');
});
module.exports = router;
With typescript, we don't use module.exports but export directly like so:
import express from "express";
export const router = express.Router();
router.use('/', (req, res, next) => {
res.send('cool');
});
Then we can get the router with
import {router} from './api'
this is my first post on StackOverflow!
I have a problem with a new bot I'm creating.
First of all, this is my code in app.js
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from "mongoose";
import { VERIFY_TOKEN, PORT, MONGODB_URI } from './config';
import { botLogic } from './logic';
mongoose.Promise = global.Promise;
mongoose.connect(MONGODB_URI, { useMongoClient: true });
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Correcly deployed!');
});
app.get('/webhook', (req, res) => {
if(req.query['hub.verify_token'] === VERIFY_TOKEN) {
res.send(req.query['hub.challenge']);
}
res.send('Invalid credentials');
});
app.post('/webhook/', async (req, res) => {
try {
await res.sendStatus(200);
await Promise.all(req.body.entry.map(async entry => {
await Promise.all(entry.messaging.map(async update => {
console.log(`Received update from ${update.sender.id}`);
await botLogic(update);
}));
}));
} catch (e) {
console.error(e);
}
});
app.get('*', (req, res) => {
res.status('404').send('Nothing interesting here');
});
app.listen(PORT, function() {
console.log('running on port', PORT);
});
I created the app on the Facebook Developer page and the webhook is linked:
Facebook developer page: webhook
If you go on https://my-personal-bot.herokuapp.com/ it should say
correctly deployed
but If you go here
https://my-personal-bot.herokuapp.com/webhook
is gonna say:
Invalid credentials
and if I log req.query the result is an empty object.
Logs screenshot
I built a couple of bots before and this initial setup was quite straightforward, however, I this particular case, I can't figure out where is the problem. The API version that I'm using is v2.11, it's the only difference with my previous bots.
Thank you in advance for any advice!
the body of the webhooks from Facebook is only json encoded, so get rid of the line that adds url encoding:
app.use(bodyParser.urlencoded({extended: false}));
Also the request is encrypted using your app secret, so you'd need to decode that before using bodyParser.json()
app.use(xhub({algorithm: 'sha1', secret: process.env.APP_SECRET }));
of course you wanna set your env variable APP_SECRET in the heroku console
For a complete example usage of webhooks, look at https://github.com/mduppes/webhooks_test/blob/master/index.js