Anthony
Anthony

Reputation: 388

Webpack not detecing proxy for local development

I'm having trouble getting a little proxy working with my React app. I'm trying to use a little express server to keep some API keys secret so that my application can make use of a 3rd party API (the github API to be specific). I have a small express app running that I can query to get the API keys out of a .env file and attach those keys to my request to the 3rd party API.

Presently, I am able to start the front-end application and the express app simultaneously, and I can query the express app and get a response using my browser.

I'm trying to configure webpack to proxy my requests through this express app. In my webpack.config.js file I have:

//
devServer: {
    port: 8080,
    proxy: {
      '/api/**': {
        target: 'http://localhost:3000',
        secure: false,
        changeOrigin: true
      }
    }
  }
//

Front-end application is running on port 8080, and my Express app is running on port 3000, both on the localhost.

In my React App, for trying to test whether this proxy is being detected/used, I have the following in a component:

//
handleSubmit(event) {
    event.preventDefault();
    fetch('/api/secret')
      .then(res => {
        console.log('RES: ', res)
        res.json()
      })
      .then(data => {
        console.log("Data: ", data)
        return JSON.stringify(data)
      })
    this.props.onSubmit(this.state.username)
  }
//

The backend code is super simple at the moment, but here it is:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();

// Initialize app
const app = express();
const port = 3000;

// Configure
app.use(bodyParser.json())
app.use(cors())



app.get('/secret', (req, res) => {
  res.status(200)
  res.send({ aSecret: process.env.<API_KEY> })
})

app.listen(port, () => console.log(`App is running on port ${port}`))

In my package.json I have the following (relevant script and dependencies):

...
...
"start": "concurrently --kill-others \"webpack-dev-server\" \"npm run server\"",
    "server": "nodemon server/index.js"
  },
  "babel": {
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
    ]
  },
  "dependencies": {
    "prop-types": "^15.7.2",
    "react": "^16.13.0",
    "react-dom": "^16.13.0",
    "react-icons": "^3.9.0"
  },
  "devDependencies": {
    "@babel/core": "^7.8.7",
    "@babel/preset-env": "^7.8.7",
    "@babel/preset-react": "^7.8.3",
    "babel-loader": "^8.0.6",
    "body-parser": "^1.19.0",
    "concurrently": "^5.1.0",
    "cors": "^2.8.5",
    "css-loader": "^3.4.2",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "html-webpack-plugin": "^3.2.0",
    "nodemon": "^2.0.2",
    "style-loader": "^1.1.3",
    "svg-inline-loader": "^0.8.2",
    "webpack": "^4.42.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3"
  },
  "proxy": "http://localhost:3000"
}

As you can see, in the component I'm (attempting to) making a request to api/secret and hoping to get back in the response the API key that I have stored in my .env.

When I query this route in my browser using fetch('http://localhost:3000/secret') I am able to access the API key successfully, so I know that when I run the npm run start script that both the React application and the Express application are starting up simultaneously.

When I click the button in my React component that sends a request to /api/secret I get the following output in the browser console (in keeping with the console logs I have in the react component at the moment): Console output indicating a request made to the URL <code>http://localhost:8080/api/secret</code>, further showing that the proxy I'm trying to set up is not being detected

I'm just not sure at this point what I'm doing wrong with the proxy configuration in the devServer webpack configuration.

I can see that the hostname is being automatically prepended to the /api/secret in the fetch within the React component.

Stated Goal: Webpack successfully detects the proxy server I'm using to server requests to the 3rd party (GitHub) API.

I apologize if this question is a repeat, I've spent several hours researching and fiddling with this configuration and have been unsuccessful in finding out how to configure this. This is my first attempt at spinning up a little proxy server as well. Thanks in advance for any help!

Upvotes: 0

Views: 526

Answers (1)

Siri
Siri

Reputation: 1126

You need to return res.json()

handleSubmit(event) {
    event.preventDefault();
    fetch('/api/secret')
      .then(res => {
        console.log('RES: ', res)
        return res.json()
      })
      .then(data => {
        console.log("Data: ", data)
        return JSON.stringify(data)
      })
    this.props.onSubmit(this.state.username)
  }

Upvotes: 1

Related Questions