How to serve an index.html in react js in http2 - express

How to serve an index.html in react JS in http2....
like below express code
const express = require('express');
const app = express();
app.use(express.static(`${__dirname}/../build`));
app.all('*', (req, res) => {
res.status(200).sendFile(`${__dirname}/../build/index.html`);
});
console.log('server is running')
const port = 2002;
app.listen(port, () => console.info(`app listening to port ${port} `));

Related

Next js custom server problem when deployed to cloud

I've created a next js custom server feature using express
Everything works fine on localhost but when deployed to google cloud
only the routes from page/api directory is working.
the /test route is not working
Server
const express = require('express')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.get('/test', (req, res) => {
res.send('This is a test page')
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, (err) => {
if (err) throw err
console.log('Now serving on port 3000')
})
})
package.json
"start": "NODE_ENV=production node server.js",

Can't receive a response message when using proxy-middleware between react ui and express backend

I see that the request sent from the ui created using React is forwarded to the backend, but I can't get the response from the ui. There may be details that I missed as I am very new to these issues, thanks in advance :)
//react Login.js
function Login() {
const fetch = actions.fetchUser();
async function handleSubmit() {
try {
fetch();
} catch (err) {
console.error('err', err);
}
}
export default Login;
//index.js
import axios from 'axios';
export const fetchUser = () => async () => {
await axios.get('/api/login');
};
//setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
['/api'],
createProxyMiddleware({
target: 'http://localhost:5000',
}),
);
};
//express app.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 5000;
app.use(cors());
app.use(bodyParser.json());
require('./routes/login')(app);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
// espress login.js
module.exports = app => {
app.get('/api/login', (req, res) => {
console.error('express login');
res.send('login');
});
First of all, do not mix cjs and mjs import/exports.
second of all, you export your middleware but never register/use it. At least your code does not show that part.
Here is very minimal example how you can proxy your react UI via express.
const express = require('express');
const proxy = require('express-http-proxy');
const app = express();
app.get('/api', (req, res) => {
res.send({my: 'data'});
});
// register other routes here
app.use(proxy('http://127.0.0.1:3000'));
app.listen(5000, '0.0.0.0', () => {
console.log('Server is running at http://127.0.0.1:5000');
});
React app content will be available on http://127.0.0.1:5000 with your routes.
And http://127.0.0.1:5000/api will be your express route.
Note: I assume your react app runs on the port 3000

i18next dropdown select without reactjs

I need to create a dropdown in order to select languages in the website. I only use nodejs not react. How can I create it? My codes are at the below.enter image description here
const express = require('express');
const app = express();
const ejs = require('ejs');
const i18next = require('i18next');
const Backend = require('i18next-fs-backend');
const i18nextMiddleware = require('i18next-http-middleware');
i18next
.use(Backend)
.use(i18nextMiddleware.LanguageDetector)
.init({
fallbackLng: 'tr',
lng: 'tr',
backend: {
loadPath: './translate/{{lng}}.json',
},
});
app.use(i18nextMiddleware.handle(i18next));
app.use(express.json());
app.set('view engine', 'ejs');
const stdI18next = { t: i18next.t.bind(i18next.t) };
app.get('/', (req, res) => {
res.render('index', stdI18next);
});
app.get('/test', (req, res) => {
res.render('test', stdI18next);
});

Failed to load resource: the server responded with a status of 404 (Not Found) on routing

I am trying to route in my project. I want that on clicking connect button the rooms page should get rendered. Home page is working fine but as soon I as click connect it shows Cannot GET /rooms/0b2636b5-c254-47f4-ade8-9e6b745a96d1.The code works fine when instead of routing to rooms it is on root url.
I am new to web development and I tried reading other questions on similar problem but couldn't understand.
Server side(Server.js):
const express = require('express');
const app = express();
const server = require('http').Server(app);
const { v4: uuidV4 } = require('uuid');
const io = require('socket.io')(server);
const { ExpressPeerServer } = require('peer');
const peerServer = ExpressPeerServer(server, {
debug: true
});
app.use('/peerjs', peerServer);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/', (req, res) => {
res.render('home');
})
app.get('/rooms', (req, res) => {
res.redirect(`/rooms/${uuidV4()}`);
})
app.get('/rooms:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
server.listen(3000);
Client Side(script.js)
const socket = io('/rooms');
const videoGrid = document.getElementById('video-grid');
var peer = new Peer(undefined, {
path: '/peerjs',
host: '/rooms',
port: '3000'
})
Navigation bar on home.ejs
<nav class="nav">
<li class="nav-link">
Connect
</nav>
room.ejs
<script>
const ROOM_ID = "<%=roomId%>"
</script>
<script src="/socket.io/socket.io.js" defer ></script>
<script src="script.js" defer></script>
Structure of file
public
-script.js
views
-home.ejs
-room.ejs
server.js
You're really close to it, just 1 mistake in this block:
app.get('/rooms:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
It should be:
app.get('/rooms/:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
Express documentation page here in case you need it (section Route parameters).

ES6 Router.use() requires a middleware function but got a Object

Now I worked with Node.js + Express to make some api server.
I installed babel-preset-latest to use ES6 statement.
However, When I write some code, it throws error ->
Router.use() requires a middleware function but got a Object
[index.js]
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send('main');
});
app.use('/api', require('./api/auth'));
app.listen(3000, () => {
console.log("Express Running port 3000")
})
[/api/auth/index.js]
import express from 'express';
const router = express.Router();
router.get('/', (res, req) => {
res.send('auth main')
});
export default router;
In ES6, module.export can replace to export.
But it throw errors. So, after I replace export default router; to module.exports = router;, It works perfectly.
Why do I get this error? Is there any syntax error?
Thanks.
[SOLVED]
[index.js]
import express from 'express';
import bodyParser from 'body-parser';
import authRouter from './api/auth';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send('main');
});
app.use('/api', authRouter);
app.listen(3000, () => {
console.log("Express Running port 3000")
})
[/api/auth/index.js]
import express from 'express';
const router = express.Router();
router.get('/', (res, req) => {
res.send('auth main')
});
export default router;
in index.js, Define import statement -> import authRouter from './api/auth';
and replace app.use('/api', require('./api/auth');
to
app.use('/api', authRouter);