Home > Software design >  how to add flask localhost to existing react app
how to add flask localhost to existing react app

Time:09-28

package.json code

I want to add flask localhost to it but I already have the localhost use in react, so how to add the two proxy parameter, or is there any way to do it?

CodePudding user response:

  1. create a file setupProxy.js in react src folder ,
  2. install npm package "http-proxy-middleware"
  3. delete proxy from package.json

in setupProxy.js

  const { createProxyMiddleware } = require("http-proxy-middleware");
    
    module.exports = function (app) {
      app.use(
        createProxyMiddleware("/your route", {
          target: "http://localhost:/", //url of your server 
        })
      );
      app.use(
        createProxyMiddleware("/your route", { 
          target: "http://localhost:/",//url of your server
        })
      );
    };

CodePudding user response:

any idea how can I change the index file when using "http-proxy-middleware"?

require("dotenv").config();
const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");

const querystring = require("querystring"); //let us parse and stringigy query string
const app = express();
const axios = require("axios");
const path = require("path");

// Priority serve any static files.

const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const REDIRECT_URI = process.env.REDIRECT_URI;
const FRONTEND_URI = process.env.FRONTEND_URI;
const PORT = process.env.PORT || 8889;
/**
 * Generates a random string containing numbers and letters
 * @param  {number} length The length of the string
 * @return {string} The generated string
 */
const generateRandomString = (length) => {
  let text = "";
  const possible =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for (let i = 0; i < length; i  ) {
    text  = possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
};

const stateKey = "spotify_auth_state";

app.use(express.static(path.resolve(__dirname, "./client/build")));

app.get("/login", (req, res) => {
  const state = generateRandomString(16);
  res.cookie(stateKey, state);

  const scope = ["user-read-private", "user-read-email", "user-top-read"].join(
    " "
  );
  const queryParams = querystring.stringify({
    // querystring.stringify() take object with keys and value
    client_id: CLIENT_ID, // and serializes them into query string
    response_type: "code",
    redirect_uri: REDIRECT_URI,
    state: state,
    scope: scope,
  });
  res.redirect(`https://accounts.spotify.com/authorize?${queryParams}`);
});

app.get("/callback", (req, res) => {
  const code = req.query.code || null; // req.query: object containing a property for each query string parameter a route
  // if route : callback?code=abc123&state=xyz789
  // => req.query.code is abc123 & req.query.state is xyz789

  axios({
    //send the request when invoked
    method: "post",
    url: "https://accounts.spotify.com/api/token",
    data: querystring.stringify({
      grant_type: "authorization_code",
      code: code,
      redirect_uri: REDIRECT_URI,
    }),
    headers: {
      "content-type": "application/x-www-form-urlencoded",
      Authorization: `Basic ${new Buffer.from(
        `${CLIENT_ID}:${CLIENT_SECRET}`
      ).toString("base64")}`,
    },
  })
    .then((response) => {
      if (response.status === 200) {
        const { access_token, refresh_token, expires_in } = response.data;

        const queryParams = querystring.stringify({
          access_token,
          refresh_token,
          expires_in,
        });

        //redirect to react app
        res.redirect(`${FRONTEND_URI}/?${queryParams}`);

        //pass along tokens in query params
      } else {
        res.redirect(`/?${querystring.stringify({ error: "invalid_token" })}`);
      }
    })
    .catch((error) => {
      res.send(error);
    });
});

app.get("/refresh_token", (req, res) => {
  const { refresh_token } = req.query;
  axios({
    method: "post",
    url: "https://accounts.spotify.com/api/token",
    data: querystring.stringify({
      grant_type: "refresh_token",
      refresh_token: refresh_token,
    }),
    headers: {
      "content-type": "application/x-www-form-urlencoded",
      Authorization: `Basic ${new Buffer.from(
        `${CLIENT_ID}:${CLIENT_SECRET}`
      ).toString("base64")}`,
    },
  })
    .then((response) => {
      res.send(response.data);
    })
    .catch((error) => {
      res.send(error);
    });
});

// All remaining requests return the React app, so it can handle routing.
app.get("*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "./client/build", "index.html"));
});

app.listen(PORT, () => {
  console.log(`express app listening at http://localhost:${PORT}`);
});
  • Related