I have an app with front end react and backend node. The backend is tested with postman and working fine. the front end ui is tested with static data. Now I have set up a proxy with the react part to connect to the backend node.
My react app is runnning on port 3000
my node is running on port 5000.
When I request a route on my backend from my front end the app does not utilize the proxy set up Instead it gives me a Bad request error.
My front end is in client folder .Please help.
the project can be found on the following github link
https://github.com/prashantbhat84/mern-contactkeeper
Please help
It seems to be a cross-origin problem. There are two ways to solve cross-origin problems in node server,
Using cors node module
First install cors module. npm install cors
and then use it inside your app
const Express = require("express");
const BodyParser = require("body-parser");
const Cors = require("cors");
const app = Express();
app.use(Cors());
app.use(BodyParser.urlencoded({ extended: false }));
app.use(BodyParser.json());
app.listen(3001, 'localhost', (err) => {
if(err) {
console.log(err);
process.exit(-1);
}
console.log("Server listen port 8083");
});
simply use following headers
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
next();
});
NPM uses a configuration file and it can be added to via the command line npm config set. The key to getting it right is the spelling of the settings. This has bit me so many times now! Getting npm to work behind a proxy requires setting the proxy and https-proxy settings. The key is noticing the - (dash) is not an _ (underscore).
Open an command prompt or terminal session and run the following commands to configure npm to work with your web proxy. The commands use domain_name.com as the address and 8080 as the port.
npm config set proxy http://domain_name.com:8080
npm config set https-proxy http://domain_name.com:8080
Related
I have an app that run normally in local development but when I deploy it (Ubuntu 21.x server) I run node/pm2 start (even installed nodemon to try) I get 404 error(not my 404 page). That how I deployed it after logging to server:
sudo apt update
sudo apt upgrade
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
git clone (repo)
cd (repo)
npm install
then I run it with
node app.js
//or
pm2 start app.js
//even using nodemon
nodemon app.js
and I installed Nginx and I get their welcoming HTML when I refer to IP address but I get 404 when I go the project port 3000
that's my server code except the POST req:
const express = require('express');
const helmet = require('helmet');
const compression = require('compression');
const bodyParser = require('body-parser');
// express app
const app = express();
app.use(helmet);
app.use(compression());
// bodyparser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// listen for request
app.listen(process.env.PORT || 3000);
// miidleware static files
app.use(express.static('public'));
app.use(express.static('script'));
app.get('/', (req, res) => {
res.sendFile('./views/index.html', { root: __dirname });
});
app.use((req, res) => {
res.status(404).sendFile('./views/404.html', { root: __dirname });
});
spent around 12 days trying so would appreciate help very much.
It seems that the server you have deployed on has an open port 80, but not port 3000.
If you want to access your express app via port 3000, you need to open the port on the Ubuntu server. How to do this depends on a vast number of variables from where the server is located to what firewall you are using.
If what you are trying to do is have your express app shown by Nginx on port 80, you will need to create a reverse proxy using Nginx.
To do this, read up on this here. There are too many variables for us to help further
New to all of this so this might be the wrong setup. I have set up one project which uses node to connect to a postgreSQL. This works and I can start this from VS Code using:
node index.js
and the response is:
App running on port 3000.
Another project is a client and has been created Vue. This is started using
npm run serve
The response is:
App running at:
- Local: http://localhost:8080/
The Vue client gets data from a source using the code below and then displays it. In this example it uses some dummy data and works fine.
created: function () {
axios
.get('https://jsonplaceholder.typicode.com/users/')
.then(res => {
this.users = res.data;
})
}
However if I change the source above to communicate with the local postgreSQL database server:
.get('http://localhost:3000/users/')
I quite rightly get the security issue in the browser console when trying to connect:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://localhost:3000/users/. (Reason: CORS
header 'Access-Control-Allow-Origin' missing)
So how do I intergrate the node.js part and the vue client part?
UPDATE
The answer to the question is below but I changed very slightly. The following was added to the index.js file (the node postgreSQL part). It is importing cors and saying allow conneciton from localhost:8080. Works perfectly:
import cors from 'cors';
const corsOptions = {
origin: 'http://localhost:8080'
};
You have to install lib cors. For that in your project folder just run the command:
npm i --save cors
After that lib is installed you should import and configure in your server application. To enable your front-end communicate with server side application.
const express = require('express');
const logger = require('morgan');
const cors = require('cors'); //<--install this lib
const app = express();
cors({ credentials: true, origin: true });//enable some headers for handling authentication tokens
app.use(cors());//use in your server
app.use(express.json());
if (process.env.NODE_ENV !== 'test') { app.use(logger('dev')); }
app.use(require('./server/index'));
module.exports = app;
As stated by the documentation, when you use the function cors() its equivallent to:
{
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204
}
I have a PHP site https://example.com.
I have a MEAN stack application subdomain http://team.example.com. It uses APIs provided by nodejs on port 3000.
I'm facing a problem when running the application on http://team.example.com where the Nodejs API is not reachable .
added the following to Apache Config File:
ProxyPass /node/ http://localhost:3000/
I am sending api request from angular side with the following:
team.example.com/node/users/login
APIs reached successfully via postman , but fails on browser
How can I solve this problem?
I think you have CORS issue, I'm assuming that you are using express framework in your node service.
See the following sample code to know how to solve CORS issue for browser.
var http = require('http');
var express = require('express');
var app = express();
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.post('/test-cors', function (req, res) {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify({ 'status': "OK" }));
});
// Create http server and run it
var server = http.createServer(app);
server.listen(8081, function() {
console.log("Listening on 8081");
});
In above sample code you need to focus on following code lines:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
Blockquote
For using the proxy you have to enable the proxy module in apache. After that restart the apache.
If you are using ubuntu os run following command
sudo a2enmod proxy &&
sudo a2enmod proxy_http
After this, you have to run
sudo service apach2 restart.
Edit to add picture of exact error, and to provide more info
When I click on main.35...js in the error message in the console, it shows me the source code to my index.html, all of it with the red underline, but I don't see the erroneous syntax there:
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"><meta name="theme-color" content="#000000"><link rel="manifest" href="/manifest.json"><link rel="shortcut icon" href="/favicon.ico"><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"><title>BoGoodSki.com</title><link href="/static/css/main.4d5a52c0.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script type="text/javascript" src="/static/js/main.35eb4822.js"></script></body></html>
Also, in development, there is no error or warning in VSCode regarding the index.html file. I'm confused for sure.
Thanks for the help so far!
End edit
I have an app deployed to Heroku that has been working well.
Today I made some changes to the Express server to handle a simple API post request to a MongoDB instance on mLab. I had to set up CORS policy as middleware but, otherwise, I didn't make any substantial changes to the server code.
My deployment flow has been to run 'npm run build' on the Create React App client, and then use the Heroku CLI to git push from my server folder. This process has worked well. Until today.
Now, when I deploy to Heroku, it says that it publishes successfully, but the app is blank in the browser and the console says that there is a syntax error of < in the build JS file. I can't currently reproduce the error because I rolled back to a working deployment in Heroku.
Here is my server code. Can you identify what may be causing the issue? My JS build files sit in client/build/static, just like Express expects them to, so I don't know what's up.
Appreciate the help.
index.js:
const express = require('express');
const mongoose = require('mongoose');
const keys = require('./config/config');
require('./models/FormData');
var bodyParser = require('body-parser');
mongoose.connect(keys.mongoURI);
const app = express();
const FormMessage = mongoose.model('formMessages')
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post("/submitMessage", (req, res) => {
var newMessage = new FormMessage(req.body);
newMessage.save()
.then(item => {
res.status(200).send();
})
.catch(err => {
res.status(400).send();
});
});
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'))
});
}
const PORT = process.env.PORT || 5000;
app.listen(PORT);
Fixed!!
Okay. Here are the steps that I took. I'm not sure which, individually, resolved the problem. But, altogether, they worked.
First, I deleted the existing main.35...js file in my source code direetory. Actually, I deleted the entire build/static folder. And then ran "npm run build" in the client directory to rebuild the React app.
I changed the node engine in my package.json from 8.1.1 to the version I am running locally, 9.2.1.
In my index.js, I removed the conditional regarding the production environment variable because, it occurred to me that it didn't make sense to serve it up differently locally than I would in production; I think that conditional was a remnant from something I had been working on earlier in the project.
Those steps taken together have done the trick. I appreciate all who have viewed this question and given it any thought. Thanks!
I am trying to deploy my ionic2 app on Heroku. I looked at these sites:
http://blog.ionic.io/one-mean-ionic-2-todo-app-on-heroku-part-1/
https://www.joshmorony.com/building-a-review-app-with-ionic-2-mongodb-node/
https://devdactic.com/deploying-ionic-to-heroku/
and created a server.js file:
var express = require('express');
var app = express(); // create our app w/ express
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var cors = require('cors');
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
// app.use(methodOverride());
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(express.static('www'));
app.set('port', process.env.PORT || 5000);
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Since I have no models and no DB at this time, I excluded mongo and mongoose.
The server runs fine when I run it on my local machine via npm start but when I run it on heroku, I get:
Cannot GET /
on the page. Heroku Logs shows:
2017-01-04T19:56:59.385666+00:00 heroku[web.1]: State changed from starting to up
2017-01-04T19:57:00.546815+00:00 heroku[router]: at=info method=GET path="/" host=hrmghp-companion.herokuapp.com request_id=4c010120-3dce-4f99-b31c-99dc0883f314 fwd="108.44.230.178" dyno=web.1 connect=1ms service=49ms status=404 bytes=364
2017-01-04T19:57:00.549928+00:00 app[web.1]: GET / 404 19.924 ms - 13
Am I missing something in my server.js file?
Edit:
I found the issue. I had www/ in my .gitignore file. I assumed that it would rebuild the app when deploying to heroku? Is this not how it works?
Don't add www to your repository. You don't want to keep track of all those files. Instead, include "postinstall": "ionic-app-scripts build" in the scripts section of your package.json. This will rebuild the app and regenerate the www folder for you on Heroku.
Just want to add something on to Alex's answer. Make sure you either add ionic-app-scripts as a dependency (as opposed to devDependency), OR disable production mode in heroku via heroku config:set NPM_CONFIG_PRODUCTION=false
So, adding "postinstall": "ionic-app-scripts build" in the scripts section of package.json, and disabling production mode worked for me.