create-react-app causing Node.js requests to not go through proxy - node.js

I'm currently writing an app with Electron, Create-React-App, and Node.js (note: in electron, webSecurity is disabled to make CORS requests).
In my App.js file I'm trying to write a module to test proxies by sending a request to a site and checking the response, like so
var proxiedRequest=request.defaults({'proxy':"http://username:password#test.test.com:0000"})
await proxiedRequest.get(site, function(error, resp, body){
console.log(resp.statusCode)
console.log(resp)
}
Now I created a separate test.js file that I used to make sure that it was react causing the issues
const request = require('request-promise')
var proxyUrl = //working proxy here;
var proxiedRequest = request.defaults({'proxy': proxyUrl});
proxiedRequest.get('http://google.com',function(err, resp, body){
console.log(err)
console.log(resp.statusCode)
})
And I tested it with both a working and non-working proxy and got the correct responses.
My question is why is create-react-app causing the request to not be routed through the proxy? Is it due to the fact that its being hosted on https://localhost:3000 or is it actually an electron based issue?

you have to add your localhost to your Whitelabel cors in your backend if your API is made by express you can use cors lib to solve the problem cors lib

Related

React proxy not conecting to api url

when i am building a social media website, but i have run into a big problem, my api server runs on localhost:6000, and my react app runs on the default of localhost:3000, i have setup my proxy in the react app's package.json to the api url (localhost:6000), but when i make an api call using axios for example
const response = await axios.get("/api/users", body, config);
console.log(response.data);
the front end makes the api call to the localhost:300 url not my api url,
please what can i do to fix this problem it has been bugging me for the past 2 days now lol.
try setting "proxy": "127.0.0.1:6000" in your package.json file for your client.
I have 3 suggestions you could try and follow
axios.get('http://localhost:6000/api/users')
or have you tried adding this to the request?
headers: {
"accepts":"application/json"
}
and finally you could try and use this package
const { createProxyMiddleware } = require('http-proxy-middleware');
const response = await axios.get("http://localhost:6000/api/users", body, config);
console.log(response.data);
Should work, or am I missing something?

net::ERR_SSL_PROTOCOL_ERROR on http POST to express server

I'm trying to post from a react client to an express server on localhost and I get this error in google chrome.
react app: http://localhost:3000
express app: http://localhost:5000
POST https://localhost:5000/upload net::ERR_SSL_PROTOCOL_ERROR
I don't have any SSL https self signed certificate, but do I need to? I have used create-react-app inside a directory within my express application to bootstrap my front-end so I'm unaware if maybe a webpack setting somewhere is trying to handle http as https for this particular operation?
I haven't used any bootstrapping for my express js application and I'll include my server file below for reference.
const express = require ('express')
const bodyParser = require ('body-parser')
const port = 5000
var app = express()
var cors = require("cors");
app.use(cors())
app.use(bodyParser())
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
app.post('/upload', (req,res)=>{
if (req.files === null ){
return res.status(400).json({message: 'no image uploaded please try again'})
}else{
const file = req.files.file
let body = req.body
res.json({body})
}
})
I know there are a fair few questions on this issue but they weren't relevant or didn't provide me any insight. I have tried making sure the ports are allowed through my firewall aswell. I have also cleared my browser cache.
I had the same issue and changed the URL to http://localhost:5000/upload instead of using https://localhost:5000/upload.
This has been discussed in multiple posts
By default you cannot call localhost request on browsers but you can disable the security
Check here : Disable same origin policy in Chrome
I also faced the same issue and I changed the URL to http://localhost:5000/path instead of using https://localhost:5000/path
It works for me.
I had the same issue but it was with WAGMI (react hooks for web3 dev) and instead of using "https://localhost:6969" (this was the RPC url for my local node) I used "http://localhost:6969" which worked!

React - Network Error when sending POST request only when on HTTPS

I have a web application where the front-end is done with React (create-react-app) and it is deployed on Heroku. The back-end is done with node.js/express and it runs on an Amazon EC2.
I don't have any problem getting the app to work when I deploy the front-end on localhost or on Heroku if I access it with HTTP as http://myapp.heroku.com. The problem arises when I access it with HTTPS (which is the default on Heroku) as https://myapp.heroku.com. When I do so and send a request to the node.js server on the Amazon EC2, I get the following error:
Error: Network Error
Stack trace:
createError#https://myapp.herokuapp.com/static/js/bundle.js:1555:15
handleError#https://myapp.herokuapp.com/static/js/bundle.js:1091:14
Here is the part in the front-end which send the request to the node.js server:
_deflateAscii(valueAscii){
axios.post('//My-EC2-Instance-Here.compute.amazonaws.com:80/deflate/ascii', {inflatedAscii: valueAscii}).then(res => {
this.setState(
{
inflatedAscii: valueAscii,
inflatedHex: res.data.inflatedHex,
deflatedBase64: res.data.deflatedBase64,
deflatedHex: res.data.deflatedHex
},
this._setTextBoxesValues
);
}).catch((err) => {
console.log(err)});
}
Here are the modules I use on the server-side:
const express = require('express');
const cors = require('cors');
const http = require('http');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
And the part handling coming request from the front-end:
app.post('/deflate/ascii', function(req, res){
try{
console.log('request received');
var inflatedHexValue = convert.asciiToHex(req.body.inflatedAscii);
var deflatedBase64Value = deflate.asciiToBase64(req.body.inflatedAscii);
var deflatedHexValue = deflate.asciiToHex(req.body.inflatedAscii);
}catch(err){
console.log(err);
res.status(500).send(err);
}
response = {
deflatedBase64: deflatedBase64Value,
deflatedHex: deflatedHexValue,
inflatedHex: inflatedHexValue
};
res.end(JSON.stringify(response));
console.log('response sent');
});
When I get the Network Error on the front-end, the node.js server does not receive the request, but I have done some diagnostics with Wireshark and there is and handshake with the EC2 server, but the traffic ends there without any HTTP traffic:
TCP-traffic between https://myapp.heroku.com/ and My-EC2-Instance-Here.compute.amazonaws.com
Do I need SSL on the backend if the frontend is HTTPS? From this post I understood that it can also do without Do we need ssl certificate for both front end and backend?. This is just a course project anyway and there is only meaningless strings going back and forth.
When you visit your site over https in a browser, you need to disable blocking of mixed content (http and https). As a result your browser classifies the connection as not secure.
So yes it would be good to use SSL/TSL both for backend and frontend.
Alos did you try to use
res.json(response);
res.status(200).end();
or set the headers to application/json?
I recommend to put your res calls into the try catch block, because your res.end will be executed anyway.

Nodejs: running ghost in a separate express app and serving it to the main app with a proxy

My setup involves two express apps. The main app gets the blog with a route /blog from the second one using the request module as a proxy. Here are the relevant snippets:
main app: app.js:
var request = require('request');
app.use('/blog', function(req,res) {
var url = 'http://localhost:8082'+require('url').parse(req.url).path;
req.pipe(request(url)).pipe(res);
});
Ghost's app is set up to run in a directory:
app.js:
ghost().then(function (ghostServer) {
ghostServer.start();
});
config.js:
url: 'http://localhost:8082/blog'
Everything seems to be working fine, but I cannot seem to log in to the admin console. Checking network requests shows that all the POST requests are pending and eventually fail. Once it fails, I get this in both apps:
POST /blog/ghost/api/v0.1/authentication/token - - ms - -
I've tried different proxy modules, but all yield same results. I found some info about pending POST results here AngularJS + ExpressJS. Proxy POST request is pending but the setup is a little different. Help would really be appreciated, thank you!

"Mount" (run) legacy http handler in Hapi.js

I did a Node.js meetup presentation and was unable to answer this question. It is still bothering me.
Suppose I have a legacy http application or an Express.js application. It is a function, of the form
function legacy_app(request, response) {
// Handle the request.
}
Suppose I adopt Hapi.js for new versions of my application. But I have lots of debugged legacy or upstream code which I wish to integrate into the Hapi application. For example, a legacy vhost will run the legacy version, or it is accessible inside a /legacy namespace in the URL.
What is the best way to do this?
Wrapping existing HTTP node server dispatch function for use as a hapi handler is probably ok but you must add to your hapi_wrap function (at the end):
reply.close(false);
so that hapi can finish handling the request without messing with you legacy logic (https://github.com/spumko/hapi/blob/master/docs/Reference.md#replycloseoptions).
Wrapping Express handler/middleware is much more complicated because you are probably relying on some other middleware (e.g. body parser, cookie parse, session, etc.) and using some of the Express decorator that are not part of node (e.g. res.send(), res.json(), etc.).
The only way I can think to do this is manually. Just directly break the advice in the documentation: pull out the raw request and response objects and pass them to the legacy handler.
// An application built with http core.
var http = require('http')
var legacy_server = http.createServer(legacy_handler)
function legacy_handler(request, response) {
response.end('I am a standard handler\n')
}
// An express application.
var express = require('express')
var express_app = express()
express_app.get('*', function(request, response) {
response.send('I am an Express app\n')
})
// A Hapi application.
var Hapi = require('hapi')
var server = new Hapi.Server(8080, "0.0.0.0")
server.route({path:'/', method:'*', handler:hapi_handler})
function hapi_handler(request, reply) {
reply('I am a Hapi handler\n')
}
// Okay, great. Now suppose I want to hook the legacy application into the
// newer Hapi application, for example under a vhost or a /deprecated namespace.
server.route({path:'/legacy', method:'*', handler:hapi_wrap(legacy_handler)})
server.route({path:'/express', method:'*', handler:hapi_wrap(express_app)})
// Convert a legacy http handler into a Hapi handler.
function hapi_wrap(handler) {
return hapi_handler
function hapi_handler(request, reply) {
var req = request.raw.req
var res = request.raw.res
reply.close(false)
handler(req, res)
}
}
legacy_server.listen(8081)
express_app.listen(8082)
server.start()
This seems to work, although I would love if somebody who knew Hapi well could confirm that it is bug-free.
$ # Hit the Hapi application
$ curl localhost:8080/
I am a Hapi handler
$ # Hit the http application
$ curl localhost:8081/
I am a standard handler
$ # Hit the Express application
$ curl localhost:8082/
I am an Express app
$ # Hit the http application hosted by Hapi
$ curl localhost:8080/legacy
I am a standard handler
$ # Hit the Express application hosted by Hapi
$ curl localhost:8080/express
I am an Express app

Resources