I've an web application that can render sites embeded. The problem is that this site only send POST requests.
So i thought about serving it using express, then i searched a little here i got the following code to serve it, listening to all GET requests as vuetify pages:
const express = require('express');
const path = require('path');
const hostname = 'localhost';
const port = 3000;
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(__dirname, '/dist/index.html');
});
app.listen(port, hostname, () => {
console.log("Listening at http://%s:%s/", hostname, port);
});
Then I thought to add a post method to, receiving the parameters the page sends:
const express = require('express');
const path = require('path');
const hostname = 'localhost';
const port = 3000;
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(__dirname, '/dist/index.html');
});
app.get('*', (req, res) => {
res.sendFile(__dirname, '/dist/index.html');
});
app.post('/data', (req, res) => {
const id = req.body.id;
res.sendFile(__dirname, '/dist/index.html');
});
app.listen(port, hostname, () => {
console.log("Listening at http://%s:%s/", hostname, port);
});
How do i pass this argument to vue?
Is this the best way to serve vue with a post request?
You are only sending the index.html file, there are other important files generated by vue.js.
In the following file I have a working middleware to serve a vue application which is built in ../../../frontend/dist/.
https://github.com/marekvospel/libregifts/blob/next/apps/backend/src/router/index.ts
The only important thing is the 2 middleware functions. You can replace the '/api' condition with a method check.
if (req.originalUrl.startsWith('/api')) next()
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);
I am trying to add routes to my expressjs project. I am trying to make it so that when I go to 'localhost:9000/users' it returns 'User List'. Currently it shows ,'Cannot GET /users'. I have tried putting the code in users.js into server.js and replaced the router with app but that did not work.
routes/users.js:
const express = require("express")
const router = express.Router()
router.get("/", (req, res) => {
res.send("User List")
})
router.get("/new", (req, res) => {
res.render("users/new")
})
module.exports = router;
server.js:
const express = require('express')
const app = express()
const port = 9000
const userRouter = require("routes/users")
app.set('view engine', 'ejs')
app.get('/', (req, res) => {
res.render('index', {username: 'xpress'})
})
app.use("/users", userRouter)
app.listen(port, () => {
console.log(`App listening at port ${port}`)
})
I copy your code and only modify
const userRouter = require("routes/users")
to
const userRouter = require("./routes/users")
and I have the desired output
You should use "./" to refer to your files. Otherwise, Node.js will search for package "routes/users" in built-in packages, globally-installed packages, and in node_modules folder. Of course, it doesn't available in these places.
I have search a lot and I can't seem to start express js app. All I'm getting is 404 error.
Default app.js file which has http server and it works fine.
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var message = 'It works!\n',
version = 'NodeJS ' + process.versions.node + '\n',
response = [message, version].join('\n');
res.end(response);
});
server.listen();
And this is express js code which is not working. giving me 404 error.
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
server.listen();
I also tried few other combination as well.
var express = require('express');
var app = express();
app.get('/', (req, res) => res.send('Hello World!'));
var http = require('http');
var server = http.createServer(app);
server.listen();
this one also didn't work
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => res.send('Hello World!'));
server.listen();
I also tried expressjs to create it own server and it also didn't work.
const express = require('express');
const app = express();
const port = 80;
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
I also tried to remove port from app listen and not surprisingly it also didn't work.
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello World!'));
app.listen();
I also tried everything from express-js-app-listen-vs-server-listen page but not successful.
This is the error I get
For others with the same A2 Hosting issue, the solution is actually so easy...
The problem with the application running the NodeJS deployment on cPanel. Phusion Passenger does not use the root path as '/', but as '/yourAppURL'. So in your NodeJS code, you have to add the specified AppURLPath to the call when using Express...
e.g.
//Instead of
app.get('/', (req, res) => res.send('Hello World!'));
//Change to
app.get('/YourSpesifiedAppURLPath/', (req, res) => res.send('Hello World!'));
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.