Fetch in JS adds automatically the current page url, how to remove it

Viewed 1790

So im trying to make a fetch request like this:

var url = "";
const domain = window.location.host;

if (sort === "all")  {
    url = domain + "/api/post-list/all";
}
else {
    url = domain + "/api/post-list/" + sort;
}

fetch(url)
.then(response => response.json())
.then(posts => {
  
  console.log(posts);
  posts.forEach(post => update_posts(post, sort));

}); 

problem is, fetch automatically adds the current page's url, but i dont need that, so it ends up requesting like this:

http://127.0.0.1:8000/profile/127.0.0.1:8000/api/post-list/enn

when it should be just this http://127.0.0.1:8000/api/post-list/enn.

or from this http://127.0.0.1:8000/127.0.0.1:8000/api/post-list/all to this http://127.0.0.1:8000/api/post-list/all

Is there a way?

2 Answers

try this

const domain = window.location.origin

Delete the domain it s not needed as per your example

var url = "";


if (sort === "all")  {
    url = "/api/post-list/all";
}
else {
    url = "/api/post-list/" + sort;
}

fetch(url)
.then(response => response.json())
.then(posts => {
  
  console.log(posts);
  posts.forEach(post => update_posts(post, sort));

}); 
Related