Connect node.js PostgreSQL database and Vue client locally - node.js

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
}

Related

Error occured while trying to proxy to: <ip>:3000/api/v1/metadata, react app host in aws

I have created react app with nodejs backend server. In my local machine (mac) this is working fine.
But when I host this app in aws ec2 server (ubuntu) , I'm getting this error when calling the backend apis.
Error occured while trying to proxy to: <ip>:3000/api/v1/metadata
I am using http-proxy-middleware to proxy requests for backend nodejs server.
src/setupProxy.js
const createProxyMiddleware = require('http-proxy-middleware')
module.exports = function (app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://127.0.0.1:5000',
changeOrigin: true,
})
)
}
inbound rules

ionic app running on an iOS can not access API end points on aws ec2. Desktop version of the same app does. Can you help ? Is this a cors issue?

i have an app that uses ionic and cordova plugin.
Backend: MongoDB, Express & NodeJS. Backend code is hosted on AWS EC2.
Front end: Ionic and Angular (ionic CLI 5.4.16). Code is executed either on the desktop (ionic serve) or on iOS device (ionic cordova build ios --prod)
While testing the app on desktop, I am able to connect to aws hosted endpoint (user/login) and execute corresponding workflows.
However, when I run the same app code from the iOS device no connection with the endpoint is established and i get http error code 0.
Configuration:
ionic frontend url (on desktop): localhost:8100
server url: aws-instance-url/api endpoint
reverse proxy using nginx on serve side: localhost:4443
ssl certificate and key have been rightly configured for https
requests and are working
Cors settings
const express = require('express');
const cors = require('cors');
const app = express();
const whiteList = [
'http://localhost:8100',
'ionic://localhost:8100',
'ionic://*.*,
'file://*.*
];
var corsOptionsDelegate = (req, callback) => {
var corsOptions;
if (whiteList.indexOf(req.header('Origin')) !== -1) {
console.log("origin in whiteList");
corsOptions = { origin: true };
}
else {
console.log("origin NOT in whiteList");
corsOptions = { origin: false };
}
callback(null, corsOptions);
};
exports.cors = cors();
exports.corsWithOptions = cors(corsOptionsDelegate);
Note - when accessing through the iOS device the code never flows into corsOptionsDelegate if/else loop. However, when accessed through the desktop origin is found in the whitelist..
Is this CORS issues ? Has anyone tried to access api endpoints via iOS device successfully ?
Appreciate your help...

localtunnel and CORS not working properly

I am using localtunnel to expose my backend and frontend. Right now, I have a very simple setup like this one:
const httpServer = require('http').createServer();
const socketIO = require('socket.io');
const io = socketIO(httpServer, { cors: { origin: '*' } });
io.on('connection', (socket) => {
...
});
httpServer.listen(5000, () => {
console.log(`Listening on the port 5000`);
});
I then expose this backend with localtunnel with lt --port 5000. I then get the URL, set it up in my React frontend, start the frontend app running on port 3000 and then lt --port 3000. Then, when I try to connect to the backend, I keep getting this error.
Access to XMLHttpRequest at 'https://tame-mayfly-63.loca.lt/socket.io/?EIO=4&transport=polling&t=NbU6WbU' from origin 'https://spotty-robin-42.loca.lt' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
First I thought this was some error with localtunnel, but then tried with ngrok and the error is the same. I am enabling all origins from CORS, so I don't know what might be happening.
Doing curl "https://tame-mayfly-63.loca.lt/socket.io/?EIO=4&transport=polling" works, but I guess that's because CORS is ignored when making the request with cURL.
I found the solution for my problem. Looks like you first need to access to the dynamic url serving your backend and click on "Continue". After doing that, CORS won't be a problem anymore.

Problems running an Angular 9 app in NodeJS

I have a working NodeJS server and an Angular 9 app. I'm able to test the app in development mode, it works perfectly.
But, when I build the app with ng build --prod and try to access it with NodeJS server I get several errors about file load:
Refused to apply style from
'http://localhost:8080/styles.09cf2cc3740ba29d305c.css' because its
MIME type ('text/html') is not a supported stylesheet MIME type, and
strict MIME checking is enabled.
GET http://localhost:8080/runtime.689ba4fd6cadb82c1ac2.js
net::ERR_ABORTED 404 (Not Found)
I have a proxy file in the app to redirect all its petitions to NodeJS:
proxy.conf.json
{
"/api/*": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
Am I missing something?
proxy.conf.json aims to provide you an easy way to access to backend by rewriting url in development environment, by using ng serve.
For example, by accessing http://localhost:4200/api, in fact, you access http://localhost:3000/api. (so your backend).
But here, you're issue is how to serve Angular files with NodeJS.
Here is a minimal express code which serves an API endpoint /api, and also static files inside public sub-directory.
const express = require('express')
const app = express()
app.use(express.static('public'));
app.get('/api', function (req, res) {
res.send({ message: 'api ok' })
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
Copy all files generated by ng build --prod, (see inside dist folder, and your-app-name subfolder) to public folder.
node app.js
You will be able to access your Angular app at http://localhost:3000, and your Angular app will be able to access your API at http://localhost:3000/api.

Socket.io Letsencrypt and a secure connection failing on CORS

I have a simple node.js setup running socket.io >1.0.0;
fs = require('/home/node/bin/node_modules/file-system');
// Options for socket.io > 1.0.0
var options = {
allowUpgrades: true,
transports: [ 'polling', 'websocket' ],
pingTimeout: 6000,
pingInterval: 3000,
cookie: 'nom-nom',
httpCompression: true,
key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/live/example.com/fullchain.pem'),
origins: '*:*'
};
io = require('/home/node/bin/node_modules/socket.io')(8000, options);
When a client connects from a page served via http they are able to connect as expected and the socket connection is allowed. If a client tries to connect from a page served over https I get the following error;
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com:8000/socket.io/?EIO=3&transport=polling&t=MfVDWxD. (Reason: CORS request did not succeed).
Given my CORS policy is already set for *:* which should allow anything I don't understand why it's failing.
I have tried adding {secure: true} to the client connection, and I've also tried forcing a wss:// and https:// url for the connection string - all result in the same CORS error.
This is a bare socket implementation, not using any framework like express or even http.
Can someone point me in the right direction so that I can allow my clients to connect via https or ideally http and https.
you need to install cors, you can do that with npm or any other package manager
then in your nodejs app:
// require cors
const cors = require("cors");
// Use Cors As Middleware
app.use(cors());

Resources