React router not working when navigating using url - node.js

I am getting an error Cannot GET /'page' when trying to navigate using url to a path in React Router. Navigating from application works perfectly fine. Here is my server.js:
const express = require('express');
const app = express();
const port = process.env.PORT || 3001;
const path = require('path');
app.use(express.static('build'));
app.listen(port, () => {
console.log('Server is up on port: ' + port);
})
I've tried adding this code snippet to my server but it didn't work:
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, './public/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})

Related

How to modularize socketio in express

I'm using socket.io in my express application.
I have one route and view that uses socket.io on the client-side browser.
Sooner or later the socket.io code will get larger and I would like to modularize it.
This is what I have so far and it works just fine but I am wondering what is the conventional way to modularize socket.io in an express.js app?
server.js
const app = require('./app');
const PORT = process.env.PORT || 3000;
app.listen(PORT, (req, res) => {
console.log(`Listening on port: ${PORT}`);
});
app.js (took out unnecessary things)
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const { socketIo } = require('./utilities/socket.io');
const roomRoutes = require('./routes/rooms');
/* Middleware */
app.get('/', (req, res) => {
res.render('index');
});
// Routes
app.use('/users', userRoutes);
app.use('/rooms', roomRoutes);
socketIo(io);
module.exports = http;
./utilities/socket.io
module.exports.socketIo = async (io) => {
io.on('connection', (socket) => {
socket.on('join-room', (roomId) => {
socket.join(roomId);
socket.on('chat-message', msg => {
io.to(roomId).emit('chat-message', msg);
});
});
});
}

What am I doing incorrectly with my https request?

I'm learning how to build a RESTful api with Node and Express, and I am having an issue with this https request. I am trying to make a GET request to Scryfall's api (documentation here: https://scryfall.com/docs/api), but whenever I run my server and check the browser I get a message stating
"localhost didn’t send any data. ERR_EMPTY_RESPONSE".
As I'm new to using Node and Express, I'm not really sure what I am doing wrong. Here is the code for my server.js and app.js files.
//server.js
const https = require('https');
const app = require('./backend/app');
const port = process.env.PORT || '3000';
app.set('port', port);
const server = https.createServer(app); //pass the express app to the server
server.listen(port);
and
//app.js
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('https://api.scryfall.com/cards/named?fuzzy=aust+com', (req, res, next) => {
res.send('${res.body.name} is the name of the card!');
});
module.exports = app;
Any help would be greatly appreciated! Thanks in advance!
👨‍🏫 For an example, you can do it with this code below 👇:
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('/', async (req, res, next) => {
try {
const result = await axios.get('https://api.scryfall.com/cards/named?fuzzy=aust+com');
res.status(200).send(result.data);
}catch(ex) {
console.log(ex.message);
}
});
app.listen(3000, () => {
console.log('Server is up');
})
💡 From the code above, you can call the endpoint: localhost:3000 and than you will get the result.
I hope it's can help you 🙏.
You can easily make a get request like this.
const express = require('express');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');
//Expect a JSON body
app.use(bodyParser.json({
limit: '50mb' //Request size - 50MB
}));
app.get('/test', (req, res, next) => {
// do whatever you need here
res.status(200).send("ok");
});
app.listen(port, function () {
console.log(`Server is running.Point your browser to: http://localhost:${port}`)
});

syntax error: unexpected token < after replace controller in AngularJS

I use the sample of Auth0 examples AngularJS. I need to rewrite this sample and replace the controllers js file to a folder - controllers. But after doing that I get an error: syntax error: unexpected token <
I figure out that it is may server problem
server configuration on node. js is :
const express = require('express');
const app = express();
const path = require('path');
app.use('/', express.static(__dirname + '/'));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
const hostname = '0.0.0.0';
const port = 3000;
const server = app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
What problem of this server? Thank you.

Why sendFile is ignoring parameters provided for it?

I am using the following simple server.js to randomly point to two different HTML files on the server. However, it is automatically redirecting to index.html (not even in the parameters any more) and not the index1.html or index2.html.
I am not sure what I am missing here
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
app.use(express.static('public'))
app.get('/', function(req, res) {
if((Math.floor(Math.random() * 2) + 1)>1)
{
res.sendFile(__dirname + "/public/index1.html");
}
res.sendFile(__dirname + "/public/index2.html");
});
/*--------------------Routing Over----------------------------*/
app.listen(port, function () {
console.log(`Server listening on port ${port}!`);
});
As i executed your code it was looking fine to me and changing file index1.html and index2.html randomly.
If you want to change with route as well then i'll suggest below scenerio :
var express = require('express');
var app = express();
var port = process.env.PORT || 3002;
app.use(express.static('public'))
app.get('/index1.html', function(req, res) {
res.sendFile(__dirname + "/public/index1.html");
});
app.get('/index2.html', function(req, res) {
res.sendFile(__dirname + "/public/index2.html");
});
app.get('/', function(req, res) {
if((Math.floor(Math.random() * 2) + 1)>1)
{
console.log("index1");
res.redirect("/index1.html");
}
console.log("index2");
res.redirect("/index2.html");
});
app.listen(3002);
To send either index1.html or index2.html you have to use the else condition. Further, I have used the path module to create the path, which is the best practice.
var express = require('express');
var app = express();
var path = require("path");
var port = process.env.PORT || 3000;
app.get('/', function (req, res) {
if ((Math.floor(Math.random() * 2) + 1) > 1) {
res.sendFile(path.join(__dirname, "/public/index1.html"));
} else {
res.sendFile(path.join(__dirname, "/public/index2.html"));
}
});
/*--------------------Routing Over----------------------------*/
app.listen(port, function () {
console.log(`Server listening on port ${port}!`);
});

Express route returning 404 error

The express route in my node app is returning a 404 error. It works locally but on the production server it returns a 404 error (bear in mind that I changed the AJAX url to the one on my production server before uploading). My code:
server.js:
const path = require('path');
const http = require('http');
const express = require('express');
const publicPath = path.join(__dirname, '/../public');
const port = process.env.PORT || 8080;
var app = express();
var server = http.createServer(app);
app.use(express.static(publicPath));
app.post('/active-screens', function(req, res) {
res.send('route works!');
});
server.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
index.js:
function checkRoute(){
$.ajax({
url: "http://localhost:8080/active-screens",
type: "POST"
})
.success(function(data){
console.log(data);
});
}
checkRoute();
It was a CORS issue as pointed out by #WejdDAGHFOUS.
I updated my server.js to this:
const path = require('path');
const http = require('http');
const express = require('express');
const cors = require('cors');
const publicPath = path.join(__dirname, '/../public');
const port = process.env.PORT || 8080;
var app = express();
var server = http.createServer(app);
app.use(express.static(publicPath));
app.post('/active-screens', cors(), function(req, res) {
res.send('route works!');
});
server.listen(port, () => {
console.log(`Server is up on port ${port}`);
});

Resources