Socket.io and heroku CORS problem after deployment - node.js

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.

Related

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

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.

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.

Socket.io v3 Unsupported protocol version error

I'm stuck with the newer version of socket.io. Everything was fine but when I wanted to upgrade to socket.io 3, everything just broke, and currently on the client, I'm getting a 400 HTTP status code with the following JSON response -
{"code":5,"message":"Unsupported protocol version"}
Server-side config -
const io = require("socket.io")(server, {
cors: {
origin: config.clientURL,
methods: ["GET", "POST"],
credentials: true,
},
});
Client-side config -
const socket = io(backendURL, {
withCredentials: true,
});
I've tried very many things and redeployed many times but the error didn't go away.
For reference, I've these github repos -
Client in react.js - GitHub repo
Server in nodeJs and socket.io.js - GitHub repo
Looks like there may be a mismatch between versions of your socket.io-client and socket.io server.
First, update the servers with allowEIO3 set to true (added in socket.io#3.1.0)
const io = require("socket.io")({
allowEIO3: true // false by default
});
After you've upgraded the socket.io-client (latest right now is 3.1.1), you can set it back, or remove it since default is false
const io = require("socket.io")({
allowEIO3: false
});
I install old version by
npx create-nuxt-app#2.15.0
It will install nuxt with express.js in one project.
Then update npm packages by commands:
npx npm-check-updates -u
npm i
And socket.io goes well between nuxt and socket.io on server

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
}

API in nodejs Port Issue

I've created an API in nodejs backend and frontend I used reactjs as I've connected the api to my form
it shows the error
"Could Not proxy request"
Check what is the error in Chrome developer tools. It is most probably CORS issue.
If you are using NodeJs, you can use below command.
res.header("Access-Control-Allow-Origin", "*");
But this will allow CORS for all port running on your machine.
I faced the same issue when using express. I resolved it as shown below :
TRY THIS OUT IN YOUR PACKAGE.JSON CONFIGURATION refereed from create-react-app
"proxy": {
"/api": {
"target": "https://localhost:5002",
"secure": false
}
},
Also try add CORS configuration to your node check this video

Resources