How to create a proxy in React/Webpack to call an external API - reactjs

I want to issue a GET request to an external API that I do not control. Because of the security on the API, my react app cannot directly make an ajax request to the endpoint. Therefore I'm trying to create a simple proxy as demonstrated here
My package.json file looks like this:
{
"name": "my-stack",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router-dom": "^4.2.2",
"react-scripts": "1.0.13"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"proxy": {
"https://gold-feed.com/paid/*": {
"target": "https://gold-feed.com/paid",
"changeOrigin": true
}
}
}
And then my ajax request looks like this:
const apiUrl = 'https://gold-feed.com/paid/<apiID>/all_metals_json_usd.php';
jQuery.ajax({
method: 'GET',
url: apiUrl,
success: (item) => {
this.props.addItem(item);
}
});
But it doesn't appear to be doing anything. I'm still getting the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
I essentially have the same issue as documented here where he is trying to create a proxy to access the Steam api.
And just a side note, I believe the create-react-app project that I'm using is piggybacking off of webpack.

You probably figured it out by now but for others here is what worked for
me:
"proxy": {
"/proxy": {
"target": "https://mybackend.com",
"pathRewrite": {
"^/proxy" : ""
},
"changeOrigin": true
}
}
so myreact.com/proxy/my/path is redirected to mybackend.com/my/path
I think the error in your case is that you put the destination as a key for your proxy instead of path on your react server.

For my case my api was deployed on AWS, I found that setting
"changeOrigin": true
was necessary (chrome & edge worked, firefox (62.0.3) complained "Invalid CORS request").
In the documentation of webpack http proxy they say this option:
(https://github.com/chimurai/http-proxy-middleware)
Tip: Set the option changeOrigin to true for name-based virtual hosted sites.
notes:
running the api locally on same machine didn't require that for fire fox.
firefox adds header "origin" which when I removed and resent the request worked.
adding "changeOrigin" doesn't have side effects so I will be doing it from now on.
I'm not sure if it's a bug in firefox or what, anyway my final configuration was:
"proxy": {
"/api": {
"target": "<put ip address>",
"changeOrigin" : true
}
}
you should replace /api with the path of your api or rewrite the path as the answer above.

You can proxy external API to localhost, change frontend origin (localhost:3000), target server, update token if needed and run following script in node js
const express = require('express');
const proxy = require('express-http-proxy');
const cors = require("cors");
const app = express();
app.use(
cors({
origin: 'localhost:3000',
credentials: false
})
);
app.use('/', proxy('https://www.targetserver.com/', {
proxyReqPathResolver: function (req) {
return req.url;
},
proxyReqOptDecorator: function (proxyReqOpts, srcReq) {
proxyReqOpts.headers = {'Authorization': 'Replace with JWT'};
return proxyReqOpts;
}
}))
app.get('/*',function(req,res,next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.listen(4000, () => console.log(`Server Listening on port ${4000}!`));
Use it in your fontend application like this (with axios or fetch) :
axios.get('http://localhost:4000/api/route).then(x => console.log(x));

Related

HTTP 500 error upon deploying application to Google App Engine

I am using Google App Engine to deploy a test application. The deployment works fine and when I point my browser to the following URL, I receive an HTTP 500 error:
https://test-gae-365706.uc.r.appspot.com/
My application code is as follows:
const http = require('http');
const port = 8080;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Do not have an inflated sense of yourself. You are just food for worms.');
});
server.listen(port, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
My app.yaml file is as follows:
runtime: nodejs10
My package.json file is as follows:
{
"name": "app-engine",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "node app.js"
},
"engines": {
"node": "10.x.x"
},
"author": "",
"license": "ISC"
}
When I run glcoud app deploy, I do not get any errors, but when I point my browser to the URL, I get the HTTP 500 error:
Error: Server Error The server encountered an error and could not complete your request. Please try again in 30 seconds.
In the navigation pane, when I go to the Instances page, I see that no instance has been created. Could this be the problem?
Please let me know what is it that I am missing here.
You need a start script in package.json. Based on your test script, it would be something like -
"start": "node app.js"
See a sample Node App from Google
You're using the variable ${hostname} but you haven't defined it. You need to define it and provide a value like you did for port

Question about security in an electron app using express in production

I have converted a react/django application into an electron project. All data is stored externally, identical to the web app, however, one third-party token must be stored on the users machine.
To do this, I start an express server on localhost:4001 that exposes url's that read/write a few pieces of data to a file in appData.
My question is, is this safe? Essentially, is hiding node functions behind http request okay to do in electron?
I've read the security documentation, but most is in regards to using ipcMain/ipcRender communications. I'll refactor to this if I must, but what I have works and for what the app is I'm happy with that as long as it's just as secure.
Also, this SO question has made me feel better, and ive configured the server as the question suggestion.
Express localhost URLs in production for Electron app
I guess I'm just seeking validation of my current configuration, as this is not the part to be wrong on.
Here are my browser window settings. In production I will be loading the main window from a public url belonging to the original web app.
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
dev_tools: isDev,
//worldSafeExecuteJavaScript: true,
//preload: path.join(__dirname, 'preload.js')
}
})
const startURL = isDev ? 'http://localhost:3000/dashboard/' : `www.appurl.com/dashboard`}`
server.js -
as you can see CORS has been disabled and its http. For validation I'm using host-validation, and I have a jwt token already in the authorization header that I was going to send to my server for additional verification. Is this enough to offset disabling CORS?
require('dotenv').config()
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const hostValidation = require('host-validation')
const app = express();
const PORT = process.env.EXPRESS_PORT || 4001
app.use(cors())
app.use(hostValidation({hosts: ['localhost:3000', 'www.appurl.com']}))
app.use(express.json())
app.post('/upload_api_token/', (req, res) => {
fs.writeFile('filname.txt', 'Hello world')
res.send(200)
})
app.listen(PORT, () => console.log(`Server running on ${PORT}`))
And here are relevant parts of my package.json
{
"scripts": {
"start": "fuser -k 3000/tcp; concurrently \"nodemon --watch server --inspect ./server/index.js\" \"react-scripts start\"",
"build": "python prebuild.py; react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"dev": "fuser -k 4001/tcp; concurrently \"yarn start\" \"wait-on http://localhost:3000 && electron .\""
},
"dependencies": {
...,
"react": "^17.0.2",
"electron": "^18.0.4",
"electron-builder": "^23.0.3",
"electron-is-dev": "^2.0.0",
"electron-reload": "^2.0.0-alpha.1",
"express": "^4.17.3",
}

How Do You Configure Create React App to Work with Netlify Lambda Functions

I am trying to use netlify lambda functions with create react app, and it is breaking my site.
The repo was made by running npx create-react-app my-app-name, and is the standard create react app boilerplate.
File structure:
root-directory/package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"lambda": "netlify-lambda serve src/lambda"
},
"devDependencies": {
"netlify-lambda": "^2.0.15"
}
root-directory/netlify.toml:
[build]
command = "npm build"
functions = "lambda"
publish = "build"
src/setupProxy.js:
const proxy = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
proxy("/.netlify/functions/", {
target: "http://localhost:9000/",
pathRewrite: {
"^/\\.netlify/functions": "",
},
})
);
};
src/lambda/dictionary.js:
exports.handler = (event, context, callback) => {
callback(null, {
statusCode: 200,
body: "hello world",
});
};
Now, when I try to run npm run start, the app will not load.
The browser displays the error:
This site can’t be reachedlocalhost refused to connect.
When you run npm run lambda and to to the url http://localhost:9000/.netlify/functions/dictionary in the browser, the browser does display "hello, world" as expected.
Also, I am not able to use the netlify cli because when I try to install it, I get permission errors/ access denied, even when I use sudo. So, trying to get this non globally installed way to work.
I just had the same issue with the same approach with your setupProxy.js.
Then I modified the setupProxy.js to below and it worked for me
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(createProxyMiddleware('/functions/', {
target: 'http://localhost:9000/',
pathRewrite: {
"^\\.netlify/functions": ""
}
}));
};
I fixed it , please see below - its stripped down all the way to just keeping it as simple as possible with examples for even using node
https://github.com/Kirbyasdf/netlify-react-lambda-node-boilerplate

mongoDB is not working after I deployed my MERN app using Heroku, while the app works fine on my localhost

I am pulling my hair for couple of hours suffering from this issue... :(
The app works fine on my localhost, but mongoDB doesn't seem to be connected to my app.
It keeps gives me a "Type error" and I think it does Not GET a response from mongoDB.
Here's my index.js file in backend directory, and .env file is in the same directory with index.js.
// backend/index.js
const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const app = express();
const pinRoute = require("./routes/pins");
const userRoute = require("./routes/users");
const path = require("path")
dotenv.config();
app.use(express.json());
const uri = process.env.MONGO_URL;
console.log(uri)
// console.log does show uri.
mongoose
.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
.then(() => {
console.log("MongoDB Connected :)");
})
.catch((err) => console.log(err));
app.use("/api/pins", pinRoute);
app.use("/api/users", userRoute);
if (process.env.NODE_ENV === "production") {
app.use(express.static("frontend/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "../frontend", "build", "index.html"))
})
}
const port = process.env.PORT || 8800;
app.listen(port, () => {
console.log(`Backend server is running at ${port} :)`);
});
and here's my package.json
// this is in the root directory.
{
"name": "backend",
"version": "1.0.0",
"main": "backend/index.js",
"license": "MIT",
"engines": {
"node": "14.15.4",
"yarn": "1.22.10"
},
"scripts": {
"start": "node backend/index.js",
"backend": "nodemon backend/index.js",
"frontend": "cd frontend && yarn start",
"heroku-postbuild": "cd frontend && yarn install && yarn build ",
"build": "cd frontend && yarn build"
},
"dependencies": {
"bcrypt": "^5.0.1",
"dotenv": "^9.0.2",
"express": "^4.17.1",
"mongoose": "^5.12.8",
"nodemon": "^2.0.7"
}
}
This is the error I get ...
1.Try using the environment variable name as a parameter to mongoose.connect and see if it works. You do not need to assign the value to the uri constant as you did so.
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
.then(() => {
console.log("MongoDB Connected);
})
.catch((err) => console.log(err));
You could add a route to your base URL that gives you a response when you hit the same.
app.get("/", (req, res) => {
res.send("Default Route Works!");
})
EDIT:
Add this to your app.js below the middleware and whenever you redirect to
http://localhost:PORT/
eg. http://localhost:8080/ GET Request
you should see the message "Default Route Works!" on the screen. Alternatively you can send a GET request to the same end point via an API client like Insomnia, or POSTMAN.
Note: Please change your port number to where it says PORT in the localhost address.

show object in gcloud app engine console.log

When using console.log in a node app deploy on app engine, if i console.log an object, it's all written line by line.
I would like to know if it's possible to have it logged in a clean way (cf picture)
this is the result of console.log('connection: ', connection);
Idealy i would like to have my object connection appear like that :
I'm probably missing something there, if anyone can help me clear that it would be awesome ! thanks
To log objects as one entry in stackdriver, I use the client library.[1]
Using[1] this is how my app.js looks:
'use strict';
const express = require('express');
const {Logging} = require('#google-cloud/logging');
const app = express();
const logging = new Logging();
const log = logging.log('projects/[PROJECT-ID/logs/[ANY-LOG-NAME]');
const resource = {type: 'gae_app',
labels: {
'project_id': '[PROJECT-ID]',
'module_id': '[SERVICE-NAME]',
'version_id': '[ANY-VERSION-ID]',
'zone': '[CURRENT-APPENGINE-REGION]'
}
};
const entry = log.entry({resource},"Plain message one");
let dict1 = {"First name": "Jhon",
"Last name": "Smith",
"Age":32,
"Gender": "Male" };
const secondentry = log.entry({resource},{dict1});
app.get('/', (req, res) => {
console.log('Using logging client library...');
log.write([entry,secondentry]);
res.status(200).send('Printing some messages to the console').end();
});
This is my package.json:
{
"name": "node101",
"engines": {
"node": ">=8.0.0"
},
"scripts": {
"start": "node app.js",
"test": "mocha --exit test/*.test.js"
},
"dependencies": {
"express": "^4.16.3",
"#google-cloud/logging": "^7.3.0"
},
"devDependencies": {
"mocha": "^7.0.0",
"supertest": "^4.0.2"
}
}
It is important to configure properly the resource variable, otherwise your log will not appear.
I have used[2][3] to configure the resource variable, you can look at it for more information about other resources.
I deploy using the --version flag; the value of the flag is equal to the one given resource variable in app.js
gcloud app deploy --version='[ANY-VERSION_ID]'
[1] https://cloud.google.com/logging/docs/api/tasks/creating-logs#writing_log_entries
[2] https://cloud.google.com/monitoring/api/resources#tag_gae_app
[3] https://cloud.google.com/logging/docs/reference/v2/rest/v2/MonitoredResource

Resources