I'm trying to make a simple prompt authentication for my react app and I've this file server.js:
const express = require('express');
const path = require('path');
const app = express();
const basicAuth = require('express-basic-auth');
const PORT = process.env.PORT || 5000;
app.use(basicAuth({
challenge: true,
users: { 'me': 'openforme' }
}))
.listen(PORT, () => console.log(`Listening on ${PORT}`));
I want that when the user and pass are correct app use:
app.use(express.static(path.join(__dirname, '/client/build')))
to see my web page
Related
I have a React App and I use a server.js file for a Contact Form. Now my question is: In the code below what should be changed before deploying? Because my app is listening to port 5000.
const express = require("epxress");
const router = express.Router();
const cors = require("cors");
const nodemailer = require("nodemailer");
const app = express();
app.use(cors());
app.use(express.json());
app.use("/", router);
app.listen(5000, () => console.log("Server: Running"));
What should I replace that 5000 with before I deploy the app? (with Netlify if it is important)
I found the error while deploying the node app on the server. the index.js file code
const connectToDb = require("./DBconfig");
const express = require('express')
const router = express.Router();
var cors = require('cors');
connectToDb();
const app = express();
const port = process.env.PORT | 5000;
app.use(cors());
app.use(express.json());
connectToDb();
app.use( '/api/user' ,require('./routes/user') );
app.use( '/api/post' ,require('./routes/post') );
app.get('/', (req, res) => {
res.send('The site is start now')
})
if(process.env.NODE_ENV === "production"){
app.use(express.static("client/build"));
const path = require("path");
app.get("*",(req,res)=>{
res.sendFile(path.resolve(__dirname,'client','build','index.html'))
})
}
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
when I deploy the app and install the node in the server like how I install the node in server I attached the picture in which I show the installation of the node. and above I add the index.js code. It works properly in the local machine but if I hit the URL of backend backendURL it show the service unavailable error message kindly give me the solution to solve this problem.
The app works fine on GET requests. But on a POST request with body an application error occurs. I can't figure out this problem.
My app setup using express is like this:
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config()
const port = process.env.PORT || 5000
const app = express()
app.use(cors())
app.use(express.json())
app.get('/', (req, res) => {
res.send('Express Server Running...✔')
})
app.listen(port, () => {
console.log('Listening to port', port);
})
I'm using front reactjs and backend nodejs. react address is localhost:3000, and node address is localhost:5000. I already set up my proxy at react with node. this porxy setting only works in react js. but I want to use api server using routing. for example when I type the url "localhost:3000/api/hello", it route to nodejs "localhost:5000/api/hello". is is possible?
here is my nodejs code.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.port || 5000;
const fs = require('fs');
const moment = require('moment');
const data = fs.readFileSync('./database.json');
const config = JSON.parse(data);
const mysql = require('mysql');
const connection = mysql.createConnection({
host : config.host,
user: config.user,
password : config.password,
port : config.port,
database : config.database
})
const multer =require('multer');
const upload = multer({dest:'./upload'});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}))
app.use('/image',express.static('./upload'));
app.get('/api/hello',(req,res)=>{
res.send({message:"Hello Charles!"});
});
app.listen(port,()=>console.log(`Listening on port ${port}`));
As suggested you should be using the same port here for serving static assets and serving APIs. Just by adding a few lines in existing code it can be done.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.port || 5000;
const fs = require('fs');
const moment = require('moment');
const data = fs.readFileSync('./database.json');
const config = JSON.parse(data);
const mysql = require('mysql');
const connection = mysql.createConnection({
host : config.host,
user: config.user,
password : config.password,
port : config.port,
database : config.database
})
const multer =require('multer');
const upload = multer({dest:'./upload'});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}))
app.use('/image',express.static('./upload'));
// ************All static files will be servered from here.***************
app.use(express.static(path.resolve(__dirname, '../build')));
// *************** You can initialize API's here.***************
app.get('/api/hello',(req,res)=>{
res.send({message:"Hello Charles!"});
});
// *************** Fallback if no route is matching, index.html will be returned.***************
app.route('*', function (req, res) {
res.sendFile(path.resolve(__dirname, '../build/index.html'))
});
app.listen(port,()=>console.log(`Listening on port ${port}`));
In the development mode, we can specify in the package.json for proxying requests while the app is run from npm start
"proxy": "http://localhost:5000"
Both below codes serve index.html at localhost:3000/ when the server is started.
Use of express.static
const path = require('path');
const express = require('express');
const PORT = process.env.port || 3000;
const publicPath = path.join(__dirname, '../public');
var app = express();
app.use(express.static(publicPath));
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
Use of app.get
const path = require('path');
const express = require('express');
const PORT = process.env.port || 3000;
const publicPath = path.join(__dirname, '../public');
var app = express();
app.get('/',(req,res) => {
res.sendFile(publicPath + '/index.html');
})
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
So why someone would choose express.static over app.get to serve static html file. What's the use of static middle ware on express
The code that doesn't use express.static will fail when serving any other static page that isn't index.html, even if index.html included other static files(as a css) it would fail.