may be its dumb question but I can't find answer yet. :(
I made app using create-react-app, and server file:
server.js
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const PORT = process.env.PORT || 3000;
const app = express();
const p = path.parse(__dirname);
app.use(express.static('public'));
app.get('/', (req, res) => {
const filePath = path.join(p.dir, 'src', 'index.js');
fs.readFile(filePath, {encoding: 'utf-8'},(err, data) => {
if (err) {
throw err;
}
res.send(data);
});
});
app.listen(PORT, () => {
console.log(`Started at port ${PORT}`);
});
tryied to read index.js file from app src directory but all i got in browser is plain text. I can only run static files from public directory. What i did wrong and how should i run js files of react app using express in node?
You need to send the index.html file that is built by react. A browser can only open a web page from a html file.
You need to first build your react app using npm run build
Then serve it with express with something like
app.get('*', (req,res) => {
res.sendFile('/build/index.html'); // wherever react creates the index.html
});
To give you a basic idea on express,
const express = require('express')
const app = express()
app.get('', (req, res) => {
res.render('index') // index is an html file or a template (ejs, hbs, etc..)
})
// You can't directly send js files
app.get('/info', (req, res) => {
res.render('info', {
title: 'info page',
message: 'welcome to the info page'
})
})
// You can't directly send js files
app.listen(3000, () => {
console.log('Server is up on port 3000.')
})
If you want to send json
const leaderboardHistory = require("relativepath/leaderboardHistory.json")
app.get("/leaderboardhistory", function(req, res){
res.render("leaderboardhistory", {leaderboardHistory : leaderboardHistory});
});
Related
On Replit, rendering the html file using res.sendFile inside a app.get works perfectly fine, AND I am able to add logos, styles, and js logic file by passing in express.static middleware.
BUT when I try to also include the html as a static file passed to express.static middleware, the page does not render.
Here's the replit: https://replit.com/#yanichik/NodeJSandExpressFullCourseFCC#02-express-tutorial/app.js
Renders as expected when html passed in with res.sendFile:
const express = require('express'); const path = require('path');
const app = express();
// setup static & middleware // static -> file that server does NOT
have to change app.use(express.static(path.resolve(__dirname,
'./public')))
app.get('/', (req, res) => { res.sendFile(path.resolve(__dirname,
'./navbar-app/index.html')) })
app.all('*', (req, res) => { res.status(404).send('Resource not
found.') })
app.listen(5000, () => { console.log('Server listening on port
5000...') })
module.exports = app;
Now, DOES NOT render as expected when html passed in with express.static middleware:
const express = require('express'); const path = require('path');
const app = express();
// setup static & middleware // static -> file that server does NOT
have to change app.use(express.static(path.resolve(__dirname,
'./public')))
// app.get('/', (req, res) => { //
res.sendFile(path.resolve(__dirname, './navbar-app/index.html')) // })
app.all('*', (req, res) => { res.status(404).send('Resource not
found.') })
app.listen(5000, () => { console.log('Server listening on port
5000...') })
module.exports = app;
You have to specifically request for the statically exposed files like so:
https://baseURL.com/navbar-app/index.html
When you comment out get routes.
If you have your get route uncomented route then
https://baseurl.com
Will return the html file
var express = require('express');
var app = express();
var path = require('path');
var port = 3000;
app.use(express.static(__dirname));
app.get('/', (req, res) => {
res.send("Im fine");
});
app.get('/about' ,(req,res) =>{
res.sendFile(path.join(__dirname, 'modalbox.html'));
res.end();
})
app.listen(port, () =>{
console.log(`server running in https://localhost/${port}`);
})
modalbox.html isn't serving in "localhost:3000/about"
I can't find, why this html file isn't serving in this link, plz someone gimme the answer
trying to server the html file, but can't serve the file
Problem 1: The question is POST but the code is using GET.
Problem 2: Using res.end() end the response immediately while the file is being sent. res.sendFile is enough.
app.post('/about', (req, res) => {
res.sendFile(path.join(__dirname, 'modalbox.html'));
})
Problem 3: You've already serve static file using app.use(express.static(__dirname)). Just hit localhost:3000/modalbox.html and you can see your file
This is my first topic, and I'm not really that great with js, but how do I get my index.html file to show up? This is what I have.
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000
app.get("/", function (req, res) {
res.send("hello!")
});
app.listen(PORT, function () {
console.log("Server is running on localhost:" + PORT);
});
app.js and index.html are in the same directory. Thanks!
You can try using the following code into app.get function
res.sendFile(__dirname+/index.html");
I a beginner with Express js and when I reload the server to show the HTML file display "Cannot get" this is photo from the console and its show som errors
this my code server-side:
and this is a photo from git bash and the server is working
and this is my HTML code
help, please
Instead of app.route(), use app.get()
like this
const express = require("express)
const path = require("path")
const app= express()
app.get("/",(req,res)=>{
res.sendFile(path.join(__dirname, './index.html'))
})
app.listen(3000,()=>{
console.log("server running at port 3000")
})
app.route takes a string as an argument and returns a single route - you're passing a callback function, so change your route handling to the following:
// use the appropriate HTTP verb
// since you're trying to serve the `index.html` file,
// `get` should be used
app.route("/")
.get((req, res) => {
res.sendFile(path.join(__dirname, './index.html')
})
Alternatively, you could just do the following:
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, './index.html')
})
Here's a working example:
// thecodingtrain/
// index.js
// home.html
// package.json
const path = require("path")
const express = express()
const app = express()
const PORT = 3000
app.route("/")
.get((req, res, next) => {
res.sendFile(
path.join(__dirname, "./home.html")
)
})
app.listen(PORT, () => {
console.log(`Listening on port ${PORT})
})
Hope this helps.
I am trying to download array of objects in .csv format. below is the code snippet which converts an array to .csv and get stored in the file file.csv.
let downloadHelper = function(records){
let csvwriter = require('csv-writer');
createCsvWriter = csvwriter.createObjectCsvWriter;
const csvWriter = createCsvWriter({
path: './file.csv'
csvWriter.writeRecords(records).then(() => {
console.log('Done');
});
}
I need to download the file.csv to my local. tried using requests, didn't help as it is accepting only http requests. no clue, how to proceed..... Please help
You did not provide us a lot of information. But with Express you could do:
app.get("/", (req, res) => {
res.download("./file.csv", "your-custom-name.csv");
});
If this does not help you, please provide more info about the context, framework you are using and what front.
Thank you
For example, you can use Express like this:
// Libs
const express = require('express');
const http = require('http');
const path = require('path');
// Setup
const port = 8080;
const app = express();
const httpServer = http.createServer(app);
// http://localhost:8080/download
app.get('/download', (req, res) => {
res.sendFile(path.resolve(__dirname, './file.csv'));
});
// http://localhost:8080/csv/file.csv
app.use('/csv', express.static(path.resolve(__dirname, './csv_files/')));
// Run HTTP server
httpServer.listen(port, () => console.log('Server is listening on *:' + port));
If you run this snippet, you can open http://localhost:8080/download and ./file.csv would be downloaded.
Following part of code is responsible for that:
app.get('/download', (req, res) => {
res.sendFile(path.resolve(__dirname, './file.csv'));
});
Or if you want to give access to the whole directory ./csv_files/ you can do this:
app.use('/csv', express.static(path.resolve(__dirname, './csv_files/')));
Just create ./csv_files/foo.csv file and go to http://localhost:8080/csv/foo.csv.
Does it make sense to you?
PS Working example:
// Libs
const express = require('express');
const http = require('http');
const path = require('path');
const fs = require('fs');
// Setup
const port = 8080;
const app = express();
const httpServer = http.createServer(app);
// http://localhost:8080/download
app.get('/download', (req, res) => {
const filename = path.resolve(__dirname, './file' + (new Date()).getTime() + '.csv');
fs.writeFileSync(filename, 'foo,bar,baz');
res.sendFile(filename);
});
httpServer.listen(port, () => console.log('Server is listening on *:' + port));