in my express server when I click on upload button or download button I want that my server work with file system(fs) without changing web page. how to implement this code in JS?
let express = require('express');
let Fs = require('fs');
let path = require('path');
let URL = require('url');
let app = express();
let router = express.Router();
const port = 2020;
app.use(express.static('Programs'));
app.use('/', router);
router.get('/' , (req, res) => {
res.sendFile(path.join(__dirname+'/views/UiOfServer.html'));
});
router.get('/todo/download' , (req, res) => {
res.send("download page");
});
router.get('/todo/upload' , (req, res) => {
res.send("upload page");
});
app.listen(port, (err, res) => {
if(err){
console.log(`Server Error: ${err}`);
}
else{
console.log(`server started on ${port}`);
}
})
If you don't want the current page in the browser to change or refresh when clicking a button you should use AJAX.
You should use upload and download endpoints as apis and call these apis from your webpage.
You can use libraries such as jquery, axios, fetch, etc to make your job easier
Example in jquery
$.get('/todo/download').done(response => console.log(response))
Do you mean that you don't want the server to read and write continuously? If it's true, try it
fs.readFileSync(your_data_url);
it should be at the top (maybe after let router = express.Router();) because it is synchronous, and it only runs once when you load web page
Related
I have a local server that I have created to learn and practice my backend coding. Right now its in the early stages. My code is just a basic express app, i can require the json file in and i can display it but what im not sure how to do is every time the page is refreshed to load a different question?
app.js
const express = require('express')
const questions = require('./question.json')
const app = express()
const PORT = 3000
app.get('/', (req, res)=>{
res.set('Content-Type', 'text/html');
res.status(200).send("<h1>Hello</h1>");
})
app.listen(PORT, (error) =>{
console.log(`Server is Successfully Running, and App is listening on port ${PORT}`)
})
questions.json
{
"questions":[
{
"1":"Question 1?"
},
{
"2":"Question 2?"
},
{
"3":"Question 3?"
},
{
"4":"Question 4?"
}
]
}
That should work, you might want to define the path of the questions array first instead of having it written out long handed.
const express = require('express')
const questions = require('./questions.json')
const app = express()
const PORT = 3000
app.get('/', (req, res)=>{
JSON.parse(JSON.stringify(questions))
var randomObject = questions.questions[Math.floor(Math.random() * questions.questions.length)]
console.log(randomObject)
res.set('Content-Type', 'text/html');
res.status(200).send("<h1>Hello GFG Learner!</h1>");
})
app.listen(PORT, (error) =>{
console.log(`Server is Successfully Running, and App is listening on port ${PORT}`)
})
Sorry if my usage of server-related words is wrong, I'm new to this. I have two Express.js servers one on port 3000 and one on port 8000. The browser renders two different HTML files on these two ports. First I start the server on port 8000. As soon as I start the server on port 3000, I want to redirect the user viewing the site on port 8000 to a custom URL scheme to open an installed app (using "example://"). At the moment I console.log "received" on port 8000 as soon as the other server starts. How can I redirect the user to the URL "example://" so that the app opens?
This is my code for server one (port 3000):
import express, { response } from "express";
import fetch from "node-fetch";
import * as path from 'path';
import { fileURLToPath } from "url";
const touchpointApp = express();
const port = 3000;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
touchpointApp.get('/', (req, res) => {
res.sendFile('/index.html', { root: __dirname });
});
touchpointApp.listen(port, () => {
console.log('Running on Port 3000');
fetch("http://192.168.2.127:8000/launch").then(res => {console.log("Success")});
})
And this is my code for server two (port 8000):
const { response } = require('express');
const express = require('express');
const open = require('open');
const router = express.Router();
const path = require('path');
const smartMirror = express();
router.get('/', function(req, res){
res.sendFile(path.join(__dirname + '/index.html'));
});
smartMirror.use('/', router);
smartMirror.listen(process.env.port || 8000);
console.log('Running on Port 8000');
smartMirror.get("/launch", (req, res) => {
console.log("Received");
res.status(200);
})
The code is currently Frankenstein's monster because of the previous tests. I'm using NodeJS to start the servers.
This is my understanding of your intent:
User in browser visits http://somehost:8000/someUrl and gets a page
You start server on port 3000, the 8000 server somehow detects this
Subsequent requests to http://somehost:8000/someUrl are now redirected to http://somehost:3000/differentUrl and hence the user is now navigating among pages in the 3000 server. Note that the 8000 server is telling the browser: "don't look here, go to the 3000 server for your answer".
If that is your intent then you can send a redirect by
smartMirror.get("/launch", (req, res) => {
res.redirect("http://somehost:3000/differentUrl");
})
So you might have code such as
smartMirror.get("/launch", (req, res) => {
// assuming that you can figure out that the 3000 server is running
if ( the3000ServerIsRunning ) {
let originalURL = req.originalUrl;
let redirectedURL = // code here to figure out the new URL
res.redirect("http://somehost:3000" + redirectedURL);
else {
// send a local respons
}
})
I think you can do it with the location http response header.
res.location('example://...')
I'm using this code for my backend:
const express = require('express');
const app = express();
const socketIo = require("socket.io");
const io = socketIo(http);
io.on("connection", socket => {
console.log("New client connected");
socket.on("disconnect", () => console.log("Client disconnected"));
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
When I run it, it outputs the message confirming it is listening. However, on a connection it does not send any messages to the console. I'm trying to listen for connections to a React app. I have tried using other code snippets for the connection function that also claim to work as I expected, however none that I have tried have worked, including the code in the official tutorial for socket.io.
Please can anyone help?
const express = require('express')
const app = express()
const PORT = 5000
// Get to http://localhost:5000
app.get("/", (request, response) => {
// Send back some data to the client
response.send("Hello world")
})
// Post to http://localhost:5000/getRandom
app.post("/getRandom", (req, res) => {
res.send(Math.random())
})
app.listen(PORT, () => console.log(`Server running on PORT ${PORT}`))
Instead of calling the parameters request and response, people use the short form of req and res
Now start this script and go to http://localhost:5000 and you will see "Hello world" in the HTML body. That's express, simple yet powerful :)
I create an express app like this
const express = require('express')
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.post('/close', async (_, res) => {
res.status(200);
res.end();
app.close();
});
module.exports = app;
I instantiate it in another module
const myApp = require('./app.js');
myApp.listen(port, () => {
console.log(`Started server on ${port}`);
});
I want the server to shut itself down when it receives a post request to /close. At the moment, I just get a app.close is not a function error.
I know I can close a server externally like this
const server = myApp.listen(port, () => {
console.log(`Started server on ${port}`);
});
server.close();
but I want to close the server on a post request to /close, how can I do that?
To get access to your server object, try using
req.connection.server
from within your route handler.
.close() makes the server stop listening for new connections. Already-established connections are not affected. The server object emits a 'close' event when all open connections have disconnected.
process.exit() stops your whole nodejs app.
So, this code might do what you want.
app.post('/close', (req, res, next) => {
res.status(200)
res.end()
const server = req.connection.server
if (server.listening) {
server.addEventListener('close', ev => {
console.log('server closed. See ya later alligator.')
process.exit(0)
})
console.log('closing server')
server.close()
}
});
If you need to get the server object from your app object (if getting it from your req object isn't good enough), you could put in a little middleware function like this.
app.use( function adornApp( req, res, next ) {
req.app.locals.server = req.connection.server
next()
} )
Then you'll be able to get your server from app.locals.server once your middleware is first invoked.
You could use the http-terminator package to close your server. The following should do the trick. The reason we use the http-terminator is because the server won't close if it is visited via a route.
const { createHttpTerminator } = require("http-terminator");
const { initApp, app } = require("./app.js");
const PORT = 3000;
const server = app.listen(PORT, () => {
console.log(`Started server on ${PORT}`);
});
const httpTerminator = createHttpTerminator({ server });
initApp(httpTerminator);
Inside the module:
const express = require("express");
const app = express();
const initApp = (httpTerminator) => {
app.get("/close", async (_, res) => {
res.json({ message: "we closed" });
await httpTerminator.terminate();
});
};
module.exports = { initApp, app };
Note: I am using node.js, express.js, and socket.io.
I am trying to create a web page that, when a user connects, will display from one .html page (called homepage.html), but upon request, a different .html file (called lobby.html) will be sent to be displayed.
So my question is: How can I send one .html file initially, and then upon request, send a different one?
server.js -
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
http.listen(3000, () => {
console.log('listening on *:3000');
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/homepage.html');
});
This successfully sends my homepage.html to the client browser to be displayed. However, I want to be able to send an entirely different .html file in response to a client request. Am I on the right track by including something like the following in my homepage.html file...
app.get('lobby', (req, res) => {
res.sendFile(__dirname + 'lobby.html');
}
...and then in my server.js*, add something like...
let http = require('http');
const options = {
hostname: "/",
port: 3000,
method: "GET"
}
const req = https.request(options, res => {
; // How do I display the response .html file?
});
// when a button or something is clicked, request
// lobby.html
req.write();
req.end();
Thank you very much for the help!
Eric
Yes the /lobby.html is what I want to serve in response to a request for /lobby.
Then just change your server.js to this (i.e. add new get mapping):
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
http.listen(3000, () => {
console.log('listening on *:3000');
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/homepage.html');
});
app.get('/lobby', (req, res) => {
res.sendFile(__dirname + '/lobby.html');
});