Reputation: 1
I was just starting to build a server with Express, learning the workflow, and it worked just fine, then, at one point, my connection started being refused by the server. I cannot connect, nor can I send any other request to the server to check if it's alive (it happened after sending a POST request through Postman).
I made a simple POST request which would just return JSON data that was sent and after I tried it, it just shut down. I tried restarting my internet, pc and server.
I'm connecting to http://localhost:5000
, the message I get is "This site can't be reached -- localhost refused to connect."
.
My server says it's running and listening on port 5000 yet it doesn't let me connect.
I'll put my code right below this so you can tell me what could be wrong.
import express from 'express'
import mongoose from 'mongoose'
import cors from 'cors'
import userRoutes from './routes/userRoutes.js'
const app = express()
const PORT = process.env.PORT || 5000
const mongooseConnectionUrl= "url"
app.use(cors());
app.use(express.json)
app.use("/users", userRoutes);
mongoose.connect(mongooseConnectionUrl, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
})
app.listen(PORT,() => {
console.log(`Server running on port: ${PORT}`)
})
app.get('/', (req, res) => {
res.send("<h1>Hello World</h1>")
})
Upvotes: 0
Views: 1041
Reputation: 621
The problematic line is: app.use(express.json);
-> app.use(express.json());
I'm using require()
in my example solution but it does not really matter. Also I did not include your mongoose
related code.
const express = require("express");
const app = express();
const PORT = process.env.PORT || 5000;
app.use(express.json());
app.get("/", (req, res) => {
res.send("<h1>Hello World</h1>");
});
app.use("/users", (req, res) => {
res.json({ hello: "world" });
});
app.listen(PORT, () => {
console.log(`Server running on port: ${PORT}`);
});
Upvotes: 2