Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get rid of a URL in a fetch (to use kind of a variable instead)?

Tags:

reactjs

fetch

I have this function for submitting code (see gist https://gist.github.com/constantinscum/4ed753dcd681b4758a8500e4b53d925c) and I don't want to write that //https: in every source file. I was thinking about a global variable but it might be a more elegant solution for this. Do you have any idea how to do that? I want to get rid of the localhost domain URL because it will change after the app will be deployed on a server. Thank you!

like image 938
Marinescu Avatar asked Sep 09 '20 10:09

Marinescu


People also ask

What is the fetch URL?

URL Fetch. This service allows scripts to access other resources on the web by fetching URLs. A script can use the UrlFetch service to issue HTTP and HTTPS requests and receive responses. The UrlFetch service uses Google's network infrastructure for efficiency and scaling purposes.

How do you set fetch results to variables?

Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.

Does fetch work with HTTP?

The Fetch API is a modern interface that allows you to make HTTP requests to servers from web browsers.


1 Answers

You should use a proxy to the backend api url, this will allow you to just write the api url without adding server name / domaine

in development you can create setupProxy.js and use http-proxy-middleware to redirect all api calls to the server

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = app => {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:3001',
      changeOrigin: true,
    }),
  );
};

and your fetch call will look something like this

 fetch('/api/code/add')

you can read more about setup proxy Here

and for production it will depend on the tools you will use, (Nginx, Node, ...)

like image 87
Chiller Avatar answered Sep 21 '22 18:09

Chiller