Just need to access baseUrl in the post method on the code below. What is the correct method of doing so? And if you can explain to me why this does not work I would be thankful.
const API = {
baseUrl: "http://my_api_address",
post: (path, payload) => {
let headers = {
Accept: "application/json",
"Content-Type": "application/json"
};
let token = localStorage.getItem("accessToken");
if (token) {
headers["Authorization"] = "Bearer " + token;
}
alert(this); // shows undefined so I can't access this.baseUrl inside this function
return fetch(this.baseUrl + path, {
method: "POST",
headers,
body: JSON.stringify(payload)
})
.then(res => {
return res.json().then(json => ({ json, res }));
})
.then(({ json, res }) => {
if (!res.ok) {
return Promise.reject(json);
}
return json;
});
}
};
As requested:
API.post("/account/resetpassword", data)
.then(function(json) {
UI.toggleModal("#modalId");
UI.loader("hide");
UI.alert(json.success, json.message);
})
.catch(function(json) {
console.log(json);
});
The code above works if I replace this.baseUrl with "http://my_api_address" so I don't think there is any other issue.