localtunnel and CORS not working properly - node.js

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.

Related

cannot post ; post can't be made with axis on react

I am trying to make a post request in React to the server
my React app is running at port 3000 & express app is running at port 9000
React:
axios.post("/").then((response)=>{
console.log(response.data)
}).catch((e)=>{
console.log(e.response.data)
this.out = e.response.data
})
Express:
app.post("/", (req, res) => {
console.clear()
console.log(req.body)
res.end("req")
})
on the web console it says :
"Failed to load resource: the server responded with a status of 404 (Not Found)"
on the app 'postman' It runs just fine
I tried to follow this YT tutorial https://www.youtube.com/watch?v=kJA9rDX7azM
First you need to check weather you add a proxy in your React APP project Package.Json file under the private dependency name,
proxy:
'http://localhost:9000/'
Axios first look for the port you are requesting for in the current server which is in you case is / so / is also a port in frontend so it never goes for the backend be safe to go with
axios.post("http://localhost:9000/")
.then((response)=>{
console.log(response.data)
})
.catch((e)=>{
console.log(e.response.data)
})
Secondly make sure you must install the axios dependency in your react project
Seems like you forgot to add domain in the axios request.
axios.post("http://localhost:9000/").then((response)=>{
console.log(response.data)
}).catch((e)=>{
console.log(e.response.data)
this.out = e.response.data
})

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.

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());

create-react-app proxy api requests behind a corp proxy

Here is my situation,
I am creating a react app behind a corp firewall. My api server is running remotely on a different location. How to setup my proxy in the package.json so that I can hit the api servers through the corp proxy?
My configuration so far I have experimented with is this:
"proxy" : {
"/api/" : {
"target" : "http://****myapiserver.com",
"changeOrigin" : true,
"agent" : {
"host" : "pathtoproxy.com",
"port" : 80
}
}
}
I have tried several other combinations also without any luck. Anything I'm missing or wrong?
Also, my npm is configured, so that it has http and https proxy setup.
Okay, so I solved this by writing a custom proxy - so now I have 3 proxies.
React Proxy - Which will be hit when the browser makes a call for the api.
My custom proxy that is "pipe-ing" the request from react app's proxy to corp proxy.
CORP Proxy, that allows me to reach the api server I want to hit.
// React App's package.json - runs on port 3000
"proxy" : "http://localhost:3001"
// myproxy.js - runs on port 3001
var express = require('express')
var request = require('request')
const app = express();
var serverRequest = request.defaults({'proxy':'http://path2.corp.proxy.com:port'})
app.all('/', (req, res) => {
let url = "http://myserver.com/api" + req.url
req.pipe(serverRequest(url)).pipe(resp)
);
app.listen(3001);
Once I have this, I start my custom proxy as node proxy.js
Then I start my react app and everything works well, I can hit the api server.

Resources