I am trying to set up a few pages so that when a user goes to locahost:number/war . They can see the /war page. But when I run the server I get a "Cannot GET war" error on the page. I've set it up similar to this before and didnt have an issue.
I also get a "ReferenceError: __dirname is not defined" issue on the console
import express from 'express';
const app = express();
const router = express.Router();
import path from 'path';
import {getData} from './server.js'
// HTML Routes
router.get('/', (req,res)=> {
res.sendFile(path.join(__dirname, "../start.html"));
})
router.get('/war', (req,res)=> {
res.sendFile(path.join(__dirname, "../index.html"));
})
router.get('/score', (req,res)=> {
res.sendFile(path.join(__dirname, "../finalScore.html"));
})
// Data
export async function sendStats(){
app.get("/data", (req,res)=> {
const data = getData()
res.json(data)
})
app.post("/data",(req, res) => {
const {name, score} = req.body
const data = createData(name, score)
res.json(data)
} )
app.use((err, req, res, next) => {
console.log(err.stack)
res.status(500).send('Something Broke!')
})
app.listen(7171, ()=> {
console.log('Server is running on port 9191')
})
}
const data = await sendStats();
You forgot to load the router in the app:
app.use('/', router)
Related
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.
I have the problem on routers. My main route /weather working, but others routers on him don't.
app.js
const express = require('express');
const weatherRoute = require('./back/routes/weatherRouter.js');
const app = express();
app.use(bodyParser.json());
app.disable('etag');
app.use('/weather', weatherRoute);
weatherRouter.js
const router = express.Router();
router.get('/', async (req, res) => {
try {
const wholeData = await WeatherInfo.find();
res.json(wholeData);
} catch (err) {
res.json({ message: err })
}
});
router.get('/now', (req, res) => {
res.send("ITS NOT WORKING");
});
module.exports = router;
the problem is that localhost:5000/weather working perfect, but when I want to use some other routers on that Route e.g. localhost:5000/weather/now that's not working
Any ideas what I'm doing wrong ?
UPDATED :
it works, when between those routers is no others routers.
e.g.
router.get('/', async (req, res) => {
//working
}
router.post('/:add', async (req, res) => {
//working
}
router.get('/now', async (req, res) => {
//doesnt work
}
If I move /now above /add router it works perfect. Can someone explain why is this happening ?
Define actual path in path section likerouter.post('/weather/now', (re, res) => {
//Handel re
}
I found the solution.
The routers position is matter. Reference to explanation
My last router didn't work, because another router already catched him.
app.get('/:add', function (req, res) {
// this will match all /a, /b .. including /new
res.end('done!');
});
app.get('/now', function (req, res) {
// this is never called
res.end('done!!');
});
index.js
const AuthRouter = require("./Routes/Auth/signup")
app.use("/account", AuthRouter)
signup.js
router.post("/", async (req, res) => {
res.send("Signup")
})
This Code works...
But I won't like this, It's Possible in Express.js
index.js
const AuthRouter = require("./Routes/Auth/urls")
app.use("/account", AuthRouter)
urls.js
app.use("/signup", signup)
app.use("/login", login)
signup.js
router.post("/", async (req, res) => {
res.send("Signup")
})
login.js
router.post("/", async (req, res) => {
res.send("Login")
})
You could do it inline as well. I prefer it that way. like this on the server:
app.use('/users', require('../utils/api/user'))
And the route file like this called user.js in the given directory:
const express = require('express')
const router = express.Router()
router.post('/login', (req, res) => {
res.render('user', {title: 'User', user})
})
router.post('/signup', (req, res) => {
res.render('user', {title: 'User', user})
}
module.exports = router
Now the route on client side to login is /users/login and to signup is /users/signup
Yes, you can do that.
For instance, you will have to dedicate a specific file for your routes. Say routes.js like this:
import express from "express";
import { Signup } from "./";
const router = express.Router();
router.post("/signup", signup);
export { router }
Also, you have to have something like this in your server.js file:
import { router as usersRoutes } from "./api/routes/routes";
app.use("/api", usersRoutes);
Now, you can send HTTP POST requests to localhost:3000/api/signup
This below code is my first react application. After running server.js. After entering "http://localhost:8001/" I got HELLO!!. I expected after entering "http://localhost:8001/tinder/cards" url on chrome and postman too I get following error.
error message: "Cannot GET /tinder/cards".
this is my server.js file.
import mongoose from 'mongoose'
import Cors from 'cors'
import Cards from './dbCards.js'
// App Config
const app = express()
const port = process.env.PORT || 8001
const connection_url = 'mongodb+srv://admin:0tRkopC1DKm4ym4V#cluster0.iw73w.mongodb.net/tinderDB?retryWrites=true&w=majority'
// Middlewares
app.use(express.json())
app.use(Cors())
app.use('/',router);
// DB Config
mongoose.connect(connection_url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
// API Endpoints
app.get("/", (req, res) => res.status(200).send("HELLO!!"))
app.get("/hello", (req, res) => res.status(200).send("Oooooooo!!"))
app.post("/tinder/cards", (req, res) => {
const dbCard = req.body
Cards.create(dbCard, (err, data) => {
if(err) {
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.get("/tinder/cards", (req, res) => {
Cards.find((err, data) => {
if(err) {
res.status(500).send(err)
} else {
res.status(200).send(data)
}
})
})
// Listener
app.listen(port, () => console.log(`listening on location: ${port}`)) ```
try this in your app.get('/tinder/cards') section:
// Doing it the Asynchronous way
app.get('/tinder/cards', async (req, res) => {
try { // Trying for getting the cards
const allCards = await Cards.find(); // Getting the cards
res.status(200).send(allCards); // Sending the cards
} catch (error) { // Catching the error
res.status(500).send(error); // Sending the error
}
});
Try to replace cards with card in the URL. Have a look at the image for the same.
I'm learning the MERN stack and creating the typical beginner "Todo" App. When I make an axios call such as axios.post("http://localhost:4000/todos/add", newTodo) it posts fine, but when I try axios.post("/todos/add", newTodo) it doesn't.
The call obviously only works locally - how do I fix this/what am I doing wrong?
Here is todos.js file located in /routes/api folder:
const todoRouter = require("express").Router();
let Todo = require('../../models/todo');
todoRouter.route("/").get(function (req,res){
Todo.find(function(err, todos){
if (err){
console.log (err)
} else {
res.json(todos)
}
});
});
todoRouter.route("/:id").get(function(req,res){
let id = req.params.id
Todo.findById(id, function(err,todo){
if (err) {
console.log(err)
} else {
res.json(todo)
}
});
});
todoRouter.route("/add").post(function(req,res){
let todo = new Todo(req.body)
todo.save()
.then(function (todo){
res.status(200).json({"todo": "todo added successfully"})
})
.catch(function (err){
res.status(400).json("adding new todo failed")
})
})
todoRouter.route('/update/:id').post(function(req, res) {
Todo.findById(req.params.id, function(err, todo) {
if (!todo)
res.status(404).send("data is not found");
else
todo.todo_description = req.body.todo_description;
todo.todo_responsible = req.body.todo_responsible;
todo.todo_priority = req.body.todo_priority;
todo.todo_completed = req.body.todo_completed;
todo.save().then(todo => {
res.json('Todo updated!');
})
.catch(err => {
res.status(400).send("Update not possible");
});
});
});
module.exports = todoRouter;
Here is my index.js located in /routes/api folder:
const router = require("express").Router();
const todoRoutes = require("./todos");
// Todo routes
router.use("/todos", todoRoutes);
module.exports = router;
Here is index.js located in the /routes folder:
const path = require("path");
const router = require("express").Router();
const todoRoutes = require("./api");
// API Routes
router.use(todoRoutes);
// If no API routes are hit, send the React app
router.use(function(req, res) {
res.sendFile(path.join(__dirname, "../client/build/index.html"));
});
module.exports = router;
Here is my server.js file:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose')
const PORT = process.env.PORT || 4000;
const routes = require('./routes')
// Define middleware here
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
// Define API Routes
app.use(routes)
// Send every other request to the React app
// Define any API routes before this runs
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
//Connect to mongoose
mongoose.connect(process.env.MONGODB_URI || "mongodb://127.0.0.1:27017/todos", { useNewUrlParser: true });
const connection = mongoose.connection
connection.once("open", function () {
console.log("MongoDB database connection established successfully")
})
app.listen(PORT, function () {
console.log("Server is running on Port: " + PORT);
});
Just set "proxy": "http://localhost:4000" property in your package.json and all your /something requests will be directed towars your backend without having to specify the base url
you can set the baseUrl for axios to http://localhost:4000 and then relative paths should work. https://github.com/axios/axios#creating-an-instance