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")
})
Related
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.
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 have this error guys in console, if you can help me. Actually I had written that env port, but in console. it returns undefined.
const express = require('express')
const port = process.env.PORT
const { emailMessage } = require('./messageMail/sendMessage')
require('./db/db')
const app = express()
app.use(express.json())
app.post('/contact', async (req, res) => {
try {
console.log(req.body)
await emailMessage(req.body)
res.send('namaky texe hasel')
} catch (err) {
console.log(err)
res.status(500).send(err)
}
})
app.listen(port , ()=>{
console.log(port)
})
Try this:
const express = require('express')
const port = process.env.PORT || 3333;
const { emailMessage } = require('./messageMail/sendMessage')
require('./db/db')
const app = express()
app.use(express.json())
app.post('/contact', async (req, res) => {
try {
console.log(req.body)
await emailMessage(req.body)
res.send('namaky texe hasel')
} catch (err) {
console.log(err)
res.status(500).send(err)
}
})
app.listen(port , ()=>{
console.log(port)
})
This will work on your localhost on port 3333.
When you deploy your code in the server (like Heroku for example) process.env.PORT will set for the right server port.
If you want to use the .env in your project, try to use npm install dotenv and, finally, before const port = process.env.PORT you use require('dotenv').config()
I tried to set up jest, supertest, and express but failed. I have these 2 simple file
index.js
const express = require("express");
const app = express();
const port = 3000;
app.get("/", (req, res) => res.send("Hello World!"));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
and index.test.js
const express = require("express");
const app = express();
const request = require("supertest");
describe("/", () => {
test("it says hello world", done => {
request(app)
.get("/")
.expect(200)
.end(function(err, res) {
console.log("err", err);
});
});
});
when I run the test I'm getting this error.
err Error: expected 200 "OK", got 404 "Not Found"
What's wrong?
I visit localhost:3000 in my browser I can see 'Hello World!'
you should refactor index.js and create app.js
app.js
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("Hello World!"));
index.js
const app = require('./app')
const port = process.env.PORT
app.listen(port, () => { console.log(`listening on ${port}) . })
the reason why we restructure the code like this is we need to access to express app() but we do not want "listen" to be called.
in your test file
const request = require("supertest");
const app = require("../src/app");
describe("/", () => {
test("it says hello world", done => {
request(app)
.get("/")
.expect(200)
.end(function(err, res) {
console.log("err", err);
});
});
});
It's because app instance in your test is different from the one running in your index.js
Export app from your index.js:
const server = app.listen(port, () => console.log(`Example app listening on port ${port}!`));
module.exports = server;
And import in your test:
const server = require('./index.js');
// pass your server to test
...
request(server)
.get("/")
...
Not sure why the following routes: '/api/auth', '/api/auth/sudo' are not working when I hit the endpoint on my browser localhost:5003/api/auth or /api/auth/sudo
/index.js
const express = require('express')
const helmet = require('helmet')
const path = require('path')
const app = express()
const cookieParser = require('cookie-parser');
app.use(helmet())
app.use(cookieParser())
app.use(express.static(path.join(__dirname + '/client/build')))
require('./routes/authentication.js')(app)
require('./routes/product.js')(app)
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'))
});
const PORT = process.env.PORT || 5003
app.listen(PORT, () => {
console.log(`listening on port ${PORT} `)
})
/routes/authentication.js
module.exports = (app) => {
app.get('/api/auth', (req, res) => {
console.log('THIS ROUTE IS BEING HIT')
})
app.get('/api/auth/sudo', (req, res) => {
console.log('COOKIE IS SET')
})
app.get('/api/test', (req,res) => {
console.log("TESTING THIS ROUTE TO SEE IF WORKS")
})
}
Only the /api/test route works.
when the routes are moved to index.js then they all work.