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!
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.
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.
The Fetch API is a modern interface that allows you to make HTTP requests to servers from web browsers.
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, ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With