I have a simple function that sends json to a server in order to follow a user. Let me know if there’s an easier way, but this is the best way I’ve found that allows me to use a csrf token. Everytime the function runs it says “Uncaught TypeError: response.json is not a function”. I have no idea why…
Here is my function below:
function follow_user(user_id) {
const fields = {
csrf_token: {
input: document.getElementById('csrf_token'),
error: document.getElementById('csrf_token-error')
}
};
const response = fetch('/_follow_user/'+user_id, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
csrf_token: fields.csrf_token.input.value
})
});
console.log(response.json())
if (response.ok) {
if (response.text=="followed") {
document.getElementById('follow_button').innerHTML="Unfollow";
} else if (response.text=="unfollowed") {
document.getElementById('follow_button').innerHTML="Follow";
}
} else {
//This is the part that it declares is not a function. console.log shows response as going through, but response.ok also fails...
const errors = response.json();
Object.keys(errors).forEach((key) => {
fields[key].input.classList.add('is-invalid');
fields[key].error.innerHTML = errors[key][0];
});
jFlash('Follow Failed');
}
}