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}`)
})
Related
I'm using React-ecommerce, nodejs and express. I'm using an EC2-Instance on AWS. So, when I go to ghostnft.tech, it says "Hello World", when my server is working. Even if the server is running on port 8080 and I don't open ghostnft.tech:8080. I don't know why this is happening but it works, so it's good. The problem is, when I shut down the server, it still says "Hello World" on the website. How can that be? And even now after two days the server is shut down, it still works. And when I update the server so it should say "Hello World!", it doesn't update on the website. Plus, when I first started the server and connected everything on AWS, when I go to the public IPv4-DNS address, but then with "ec2-2.32.example.aws.amazon.com:8080", it gave me from 2 out of 3 refreshes a "502 Bad Gateway". On ghostnft.tech it gave me everytime the 502. Then, after about 3 hours there wasn't any 502 on ghostnft.tech and it worked. What happened here?
Below you see my index.js, that is like the server.js.
const express = require('express');
const cors = require('cors');
require('dotenv').config({ path: './.env' });
const createCheckoutSession = require('./api//checkout');
const webhook = require('./api/webhook');
const app = express();
const port = 8080;
const server = app.listen(port, () => console.log('server listening on port', port));
server.keepAliveTimeout = 65000;
server.headersTimeout = 70000;
app.use(express.json({
verify: (req, res, buffer) => req['rawBody'] = buffer,
}));
app.use(cors({ origin: true }));
app.use(cors(corsOptions)) // Use this after the variable declaration
app.get('/', (req, res) => res.send('Hello World!!!'));
app.post('/create-checkout-session', createCheckoutSession);
app.post('/webhook', webhook);
And because of the 502 I tried this, but the website won't update:
const express = require('express');
const cors = require('cors');
require('dotenv').config({ path: './.env' });
const createCheckoutSession = require('./api//checkout');
const webhook = require('./api/webhook');
const app = express();
const port = 8080;
const server = app.listen(port, () => console.log('server listening on port', port));
server.keepAliveTimeout = 65000;
server.headersTimeout = 70000;
app.use(express.json({
verify: (req, res, buffer) => req['rawBody'] = buffer,
}));
const corsOptions = {
origin:'*',
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200,
}
app.use(cors(corsOptions)) // Use this after the variable declaration
app.get('/', (req, res) => res.send('Hello World!!!'));
app.post('/create-checkout-session', createCheckoutSession);
app.post('/webhook', webhook);
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 am new to node and express js.Today I am learning and I have initialized node server as:
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const PORT = 3000
const api=require('./routes/api')
const app = express()
app.use(bodyParser.json())
app.use(cors())
api.use('/api',api)
app.get('/', function(req, res) {
res.send('Hello from server')
})
app.listen(PORT, function(){
console.log("Server running on localhost:" + PORT)
});
I have created a folder routes inside server folder and there is api.js file which has GET method to test, whether the api is working or not.Inside api.js I have,
const express = require('express')
const router=express.Router()
router.get('/', (req, res) => {
res.send('from Api Route');
})
module.exports=router
I type node server and it is displaying me :
Server running on localhost:3000
But,when I try to get the url: http://localhost:3000/api,it is displaying me:
And,in api.js file in the arrow function sublime is showing me error in red marker as:
Replace api.use('/api',api) with app.use('/api',api)
I'm trying to understand the connection between Node.js and Express.
My Code for creating a Node.js Server:
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('./https1/key.pem'),
cert: fs.readFileSync('./https1/cert.pem')
};
const server = https.createServer(options, function(req,res){
res.writeHead(200);
res.end(`Hello world!!!!!!!!!!! \n`);
});
server.listen(3000, function(){
console.log('Server listening on port 3000 \n');
});
I run a curl operation curl -k localhost:3000 and it gives me a "Hello World" Output
My code for creating an Express Server:
// call the packages we need
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
// ROUTES FOR OUR API
var router = express.Router();
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.listen(port);
console.log('Magic happens on port ' + port);
Is it possible for us to mix both of these?
To be more specific, I would like to create my Server using the Node.js way, but create my routes using the Express way. Can I do it or should I just follow one methodology? What is the connection between Node.js and Express? I understand that Express is just a framework for Node.js but where exactly does the deviation occurs if at all any?
Can I mix and combine the two when required?
Thank you
Yes you can combine nodejs and express, but not encourage you to combine those unless you have specific purpose such as using AWS lambda or making specific OS tasks that has to be made only with pure node.
As you already know, express is just a framework. You can write code more shortly using express.
For example, to make the browser displaying Hello world,
// nodejs version
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// express version
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, (req, res) => {
res.send('Hello World!\n');
})
More easier, and intuitive.
You surely can that's the way to create a Secure HTTPS server with express and followed in most projects
const https = require('https');
const express = require('express');
const app = express();
const options = {
key: fs.readFileSync('./https1/key.pem'),
cert: fs.readFileSync('./https1/cert.pem')
};
const server = https.createServer(options, app);
app.get('/', (req, res) => {
res.send('hello world')
}
server.listen(config.port, () => {
console.log(`Express server listening on port ${port} in ${app.get('env')} mode`);
});
Now add your routes and all.
I am building a (RESTful) Node.js API, using this tutorial.
I have nade a server.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8080;
app.listen(port, () => {
console.log('We are live on ' + port);
});
I can run my server and see the message :
We are live on 8080
my index.js
const noteRoutes = require('./note_routes');
module.exports = function(app, db) {
noteRoutes(app, db);
// Other route groups could go here, in the future
};
and my node_routes.js
//create a node
module.exports = function(app, db) {
app.post('/notes', (req, res) => {
// You'll create your note here.
res.send('Hello')
});
};
index.js and node_routes.js are both inside app\routes\
I have also downloaded the post man app, to make simple requests
and I get the error
Cannot POST /notes
what am I doing wrong??
I can not figure it out!
There is an error in your server.js
You are missing require('./app/routes')(app, {});
Should be:
require('./app/routes')(app, {});
app.listen(port, () => {
console.log('We are live on ' + port);
});