Ionic Capacitor -> node.js heroku -> not working with Socket - node.js

i was try to create a chat app using ionic and node.js ... backend is hosted on heroku
Socket io Declaration..
backend - const io = require('socket.io')(http);
frontend - this.socket = io("heroku url");
but still not working ... please help soon as possible

After I run on web I was getting this error:
Access to XMLHttpRequest at 'https://sellcar24hr.herokuapp.com/socket.io/?EIO=4&transport=polling&t=O0myUBB' from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Then I searched for the solution .. I found one.
In the client-side front end I add:
this.socket = io(
"heroku url",
{
transports: ['websocket', 'polling', 'flashsocket']
}
)
It works properly.

Related

Socket.io and heroku CORS problem after deployment

I set up my socket.io server on heroku but I have problem with getting data from it to my app. I get cors error:
My app is hosted on gh-pages. Here is how my socket.io setup looks like:
const io = require("socket.io")(port, {
cors: {
origin: "https://name.github.io/",
methods: ["GET"],
},
});
What should I put in origin, should it be gh-pages link or heroku app link? How can I fix that?
This is how my request looks like:
I tried putting https://name.github.io/ or https://name.herokuapp.com/, to origin property but none of this worked
For anyone having the same problem - I just removed / after url in origin and it worked :)
You should pass { cors: true, origin: <your-client-url> } as config option.

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.

Connect node.js PostgreSQL database and Vue client locally

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
}

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