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
}))
Related
I have a React app running Express querying a remote Postgres instance. I've set up some API routes to return data. When running locally, the data is returned as application/json, however when deployed to EC2 the same queries are returned as text/html so I cannot access it.
Here's some of the server code
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const axios = require("axios");
const config = require("./config");
const path = require("path");
const db = require("./db");
const PORT = process.env.PORT || 8080;
const bodyParser = require("body-parser");
const app = express();
const pdf = require('html-pdf');
const pdfTemplate = require('./documents');
// CORS is to allow access on different domains
app.use(cors());
// parse application/json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(path.join(__dirname, "client", "build")));
// TEST ROUTE
app.get("/api", (req, res) => {
res.json({ message: "Hello from server!" });
});
// ALL USERS
app.get("/api/v1", async (req, res) => {
try {
const usersOutput = await db.query(
"select * from users"
);
res.status(200).json({
status: "success",
results: usersOutput.rows.length,
data: {
users: usersOutput.rows,
},
});
} catch (err) {
console.log(err);
}
});
// SINGLE USER
app.get("/api/v1/:id", async (req, res) => {
try {
const userDetailOutput = await db.query(
"select col1, col2 from details psl inner join users pu on psl.user_id = pu.id where pu.auth0_id = $1", [req.params.id]
);
res.status(200).json({
status: "success",
data: {
user_details: userDetailOutput.rows,
},
});
} catch (err) {
console.log(err);
}
});
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'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,
);
};
I am having some issues deploying my full stack capstone. I have both ends deployed to Vercel and Heroku respectively.I did not have any issues when running it locally. When I register a user deployed, it does POST and create that user to the db, but when I go to log in with that user I get the following CORS error:
Access to fetch at 'https://desolate-reaches-15214.herokuapp.com/api/auth/login' from origin 'https://mind-your-fitness.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
auth-api-service.js:48 POST https://desolate-reaches-15214.herokuapp.com/api/auth/login net::ERR_FAILED
Here is my App.js from the backend. I am not sure what else you guys might need to help:
require("dotenv").config();
const express = require("express");
const morgan = require("morgan");
const cors = require("cors");
const { CLIENT_ORIGIN } = require("./config");
const helmet = require("helmet");
const { NODE_ENV } = require("./config");
const workoutsRouter = require("./workouts/workouts-router");
const usersRouter = require("./users/users-router");
const authRouter = require("./authentication/auth-router");
const app = express();
const morganOption = NODE_ENV === "production" ? "tiny" : "common";
app.use(express.json());
app.use(morgan(morganOption));
app.use(cors());
app.use(helmet());
app.use("/api/auth", authRouter);
app.use("/api/users", usersRouter);
app.use("/api/workouts", workoutsRouter);
app.use(function errorHandler(error, req, res, next) {
let response;
if (NODE_ENV === "production") {
response = { error: { message: "server error" } };
} else {
console.error(error);
response = { message: error.message, error };
}
res.status(500).json(response);
});
module.exports = app;
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.