In the post method below, I am trying to access baseUrl. However, it is showing undefined. Can you help me understand why and provide a solution?
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); // This shows undefined, preventing access to this.baseUrl within the 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;
});
}
};
Here's the code where I'm calling the post method:
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);
});
I found that replacing this.baseUrl with "http://my_api_address" makes the code work fine. So, it seems the issue lies in accessing this.baseUrl.