简体   繁体   中英

Managing API endpoints for a website made with vanilla JavaScript

I have a website that I am working on using vanilla JS/HTML, I plan to eventually use docker to serve this site with nginx, and host this on some VM in the cloud.

While testing my site, I want my JavaScript to use a test endpoint running from my machine, for example http://localhost/myapi/

When running in production, I want my JavaScript to use a production endpoint, for example http://example.com/myapi/

Previously I have solved this by creating 2 different files, test_endpoint.js , and prod_endpoint.js , and copying them over simply as endpoint.js depending on an argument passed to my Dockerfile.

Is there a better way to manage test vs production endpoints given my setup?

How about setting a base url in a variable depending on the url you're on? Like this:

const api = window.location.host === 'localhost' ? 'http://localhost/myapi/' : 'http://example.com/myapi/';

And then use that variable everywhere you want to call your api:

fetch(api + 'my/endpoint')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM