I'm new to full stacking and have a Create React App hitting a single /api/verify endpoint in an Express backend.
In dev, I proxy the backend in my frontend package.json with "proxy": "localhost:8081"
DevOps needs to deploying this to a GCP nginx env and I need to make the proxy path relative so we don't have to hard code the domain in the proxy.
I have create a .env.development and .env.production but I'm not sure how to use them correctly so a local yarn start proxies localhost:8081 and a production build proxies the real domain.
I have a typical, simple Express server.js but not sure how to tie it all together.
const cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');
require('dotenv').config();
const app = express();
var corsOptions = {
origin: 'http://localhost:8081',
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(bodyParser.json());
app.disable('x-powered-by');
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// simple route
app.get('/', (req, res) => {
res.json({ message: 'Welcome to bezkoder application.' });
});
require('./routes/gallery.routes')(app);
const PORT = process.env.PORT || 8081;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
And my single route:
const { authJwt } = require('../middleware');
const galleryController = require('../controllers/gallery.controller.js');
module.exports = function (app) {
app.use(function (req, res, next) {
res.header(
'Access-Control-Allow-Headers',
'x-access-token, Origin, Content-Type, Accept',
);
next();
});
app.get(
'/api/verify',
[authJwt.verifyToken],
galleryController.fanPassGallery,
);
};
Related
I really can't get socket.io to work after deployment.
Backend:
import * as dotenv from "dotenv";
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import bodyParser from "body-parser";
import { Server } from "socket.io";
dotenv.config();
const app = express();
app.use(bodyParser.json({ limit: "15mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "15mb", extended: true }));
app.use(cors());
app.get("/", (req, res) => res.send("My app API"));
const PORT = process.env.PORT || 5000;
const SOCKET_IO_PORT = process.env.SOCKET_IO_PORT || 5500;
let server = app.listen(SOCKET_IO_PORT, () => {
console.log("Socket.io server running on port :" + SOCKET_IO_PORT);
});
const io = new Server(server, {
cors: { origin: "https://myapp.pages.dev" },
});
mongoose
.connect(process.env.CONNECTION_URL)
.then(() =>
app.listen(PORT, () => console.log(`Server running on port : ${PORT}`))
)
.catch((error) => console.log(error.message));
Frontend:
socket.current = io("https://myapp-api-production.up.railway.app");
socket.current?.on(
"getMessage",
(...) => {
...
}
);
Browser network tab:
Request URL: https://myapp-api-production.up.railway.app/socket.io/?EIO=4&transport=polling&t=OO7eSMV
Request Method: GET
Status Code: 404
Response:
Cannot GET /socket.io/
Server deployment log:
Socket.io server running on port :5698
Server running on port :
7777
You're creating two separate HTTP servers (by calling app.listen() twice). It looks like your frontend code is targeting the Express server, and not the socket.io server.
My suggestion would be to just use one HTTP server listening on PORT:
let server = app.listen(PORT, () => {
console.log("Server running on port :" + PORT);
});
(and remove the call to app.listen() in the Mongoose then() handler).
I am building one react project, it is working well in my local before I build it.
But after build, I tried to integrate with node backend, but it shows me these errors.
This is my backend code. I already build my react front project.
const express = require('express');
const cors = require('cors');
const app = express();
const path = require('path');
const nodemailer = require('nodemailer');
const port = process.env.PORT || 3000;
// Middleware for parsing requests bodies.
const bodyParser = require('body-parser');
const publicPath = path.join(__dirname, '../build');
app.get('*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
app.use(express.static(publicPath));
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/api', function (req, res) {
const result = {
name: req.body.name,
email: req.body.email,
subject: req.body.subject,
message: req.body.message
};
let mailContent = `<html><div>I would like to meet you</div><div style='display:flex'><div>User Name:</div><div> ${result.name}</div></div><div style='display:flex'><div>User email:</div><div>${result.email}</div></div><div style='display:flex'><div>Message:</div><div>${result.message}</div></div></html>`;
let mailTransporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'xxxx#gmail.com',
pass: 'xxxx'
}
});
let mailDetails = {
from: result.email,
to: 'xxxx#gmail.com',
subject: result.subject,
html: mailContent
};
mailTransporter.sendMail(mailDetails, function (err, data) {
if (err) {
console.log('Error Occurs');
} else {
console.log('Email sent successfully');
}
});
res.send();
});
app.listen(port, function () {
console.log(`Server is running at ${port}`);
});
The errors you are seeing are related to the presence of < tokens in your final code. So it is not a node problem.
Usually this kind of errors are caused by a missing compilation phase from Babel, where your JSX code is compiled into calls to React.createElement.
You can try to add Babel directly in your index.html file directly. Add inside your <head></head> section this script:
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
To fix your build, you need to post more details from your project's setup.
I am using React and Express. Here is my code in Express.
const express = require("express")
const bodyParser = require("body-parser")
const { connection } = require("./db/connection")
const user = require("./routes/user")
const product = require("./routes/product")
const rentalHistory = require("./routes/rental-history")
const cors = require("cors")
const app = express()
app.use(express.static(__dirname + "/upload"))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(cors())
app.get("/", async (req, res) => {
res.json({ message: "Carbon Copies Rest Api" })
})
app.use("/user", user)
app.use("/product", product)
app.use("/rental-history", rentalHistory)
module.exports = { app }
When I hit this link https://carbon-copies-restapi.herokuapp.com/image_1628058210309.jpeg on the frontend. It throws this CORS Error. Other routes work just fine
I had the same issue, i solved adding 'origin: true' in the cors configuration.
app.use(cors({
origin: true
}))
When I run heroku local, app working as expecting.
On production, it's not loading anything from Mlab (remote mongoDb)
Here is it
https://react-bulletin.herokuapp.com/
Just showing static react file.
here is my server file
require('dotenv').config();
// Express Stuff
const express = require('express');
const app = express();
const cors = require('cors')
const path = require('path')
// Mongo Wrapper
const mongoose = require('mongoose');
// Supporting Libraries
const bodyParser = require('body-parser');
// Globals
const dbUrl = process.env.MONGODB_URI
const port = process.env.PORT
mongoose.connect(dbUrl, {
useNewUrlParser: true,
useFindAndModify: false
});
app.use(cors())
app.use(bodyParser.json());
app.use('/', require('./Routes'));
if (process.env.NODE_ENV === 'production') {
// Serve any static files
app.use(express.static(path.join(__dirname, 'client/build')));
// Handle React routing, return all requests to React app
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
const PORT = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Running at http://localhost:${PORT}`);
I have no idea why is that.
Please any help.
PS
MONGODB_URI is added to heroku varibles.
I have a reactjs project and node.js project. Now i need to set up socket.io in my project. But after set i am getting 404 error. I tired using cross and other methods, but still i am getting the same 404 error. Thanks in advance
Index.js
const express = require("express");
const port = 3000;
const app = express();
const url = require("url");
var http = require('http').Server(app);
var io = require('socket.io')(http);
const origin = url.parse(`http://${process.env.CII_RESTURL || "localhost"}/`)
.origin;
var cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
var path = require("path");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = express.Router();
app.set("port", port);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(express.json());
app.use(express.static(__dirname + "./../../"));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With"
);
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header('Access-Control-Allow-Credentials', true);
next();
});
// create a GET route
app.get("/express_backend", (req, res) => {
res.send({ express: "YOUR EXPRESS BACKEND IS CONNECTED TO REACT" });
});
app.use("/api", router);
var getTags = require("./routes/search");
router.get("/jobSearch", plainSearch.SearchByJob);
// console.log that your server is up and running
app.listen(port, () => {
console.log(`Listening on port: ${port}`);
console.log("Application live on the hostname: " + origin);
});
router.get("/",function(req,res){
res.send("hi")
})
//io.origins(cors());
io.on('connection', function(socket){
console.log("sd");
socket.on('subscribeToTimer', function(msg){
console.log('message: ' + msg);
});
});
React component
import io from 'socket.io-client';
const socket = io("http://localhost:3000/",{
path: '/api'
});
subscribeToTimer(cb) {
alert("sd");
socket.on('timer', timestamp => cb(null, timestamp));
socket.emit('subscribeToTimer', 1000);
}
calling the subscribeToTimer function in constructor.
It seems like you have not used the right react life cycle method to listen to the sockets. Always use componentDidMount() to listen to sockets or send API requests. Try something like this.
subscribeToTimer(cb) {
alert("sd");
socket.on('timer', timestamp => cb(null, timestamp));
socket.emit('subscribeToTimer', 1000);
}
componentDidMount(){
subscribeToTimer(cb);
}