Fetch POST Unexpected end of input Erorr - javascript

I'm trying to do a POST request for authentication in Redux and I'm passing email & password as the body but it returns this error in the console:
Uncaught (in promise) SyntaxError: Unexpected end of input
I looked around for the answer and many people suggested that it might be a missing } brace but I looked for it and I don't think it's that.
Here is my fetch function.
export function loginUser(creds) {
let config = {
mode: 'no-cors',
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: `email=${creds.email}&password=${creds.password}`
};
return dispatch => {
dispatch(requestLogin(creds));
return fetch('http://localhost:4000/api/authenticate', config)
.then(response =>
response.json()
.then(user => ({ user, response }))
).then(({ user, response }) => {
if (!response.ok) {
dispatch(loginError(user.message));
return Promise.reject(user);
} else {
localStorage.setItem('id_token', user.token);
dispatch(receiveLogin(user));
}
});
};
}
The fetch POST method calls the API and I see it in the networking tab and I see the response too but the fetch request stops at .then(response => after the url and config.
It's been two days and still can't find the solution. By the way, this works fine in Postman(chrome extension), so nothing wrong with the API.
Thanks
Answer EDIT: The issue was related to CORS, so for anyone having the same issue as I did.

I solve the same question when I remove
mode: 'no-cors'
from the config.

Anyway you could simplify your snippet code to:
fetch('http://localhost:4000/api/authenticate', config)
.then(response => response.json())
.then(({ user, response }) => {
And you should might add catch method to handle an Error object.

Related

POST and GET API Request using fetch, cannot get the data

i'm trying to use this website: https://rel.ink/,
to implement a link-shortener in my webapp,
i can successfully POST a request, but what i GET back is the same object, not a shortened version.
I know it's basic stuff but i can't wrap my head around it.
The website states that i need to send more information with my GET request, but the GET requests should not contain a body yes?
Here's my code:
async function fetchNewLink() {
let newLinkJson = await postLink(input.value)
let newLink = await getShortLink(newLinkJson)
console.log(newLink)
}
function postLink(input) {
return fetch('https://rel.ink/api/links/', {
method: 'POST',
body: JSON.stringify({
url: input
}),
headers: {
"Content-type": "application/json"
}
})
.then(response => response.json())
.then(json => json)
}
function getShortLink(response) {
return fetch('https://rel.ink/api/links/' + response.hashid)
.then(result => result.json())
.then(newLink => newLink)
}
Many thanks
If what you're trying to get is the shortened version of the link, the API does not return exactly that when you make a request. However, all you need is the hashid it returns. The shortened link is the main website's url(https://rel.ink) concatenated with the hashid.
So if the API returns nJzb3n as the hashid when you make a POST request, the shortened link would be https://rel.ink/nJzb3n
I hope that helps.

Response body is null(Fetch request) [duplicate]

This question already has answers here:
Trying to use fetch and pass in mode: no-cors
(9 answers)
Closed 3 years ago.
I am trying to make a request to the bank API, and get its branches in json format.
But I get an empty response.
Response
Although, if I insert the link into the browser, I will get the json format.
https://api.privatbank.ua/p24api/pboffice?json&city=Ивано-Франковск
This is how the request works Results
Errors Error
var address = document.getElementById('address').value;
function postData(url = '', data = {}) {
console.log(url);
return fetch(url, {
method: 'GET',
mode: 'no-cors',
headers: {
"Accept": "application/json",
'Access-Control-Allow-Origin':'*'
}
}).then(response => {
console.log(response);
if (response.ok)
{
response.json()
}
else {
throw new Error('Something went wrong');
}
});
}
postData(`https://api.privatbank.ua/p24api/pboffice?json&city=${address}`, {})
.then(data => console.log(JSON.stringify(data)))
.catch(error => console.error(error));
`
You're executing this as a no-cors request. These are severely restricted and you cannot read the body for it.
See stackoverflow.com/questions/45696999/fetch-unexpected-end-of-input
Also, you're not returning the result of .json(), so your function will in all cases return a promise to undefined.
I think you are trying to fetch data using no-cors when the site doesn't provide right headers then your code will not be able to access the response
a proper explanation can be seen in how to process fetch response from an 'opaque' type?

JavaScript - Cannot GET /api/list

I am working on a website where a user should be able to post items to a list. Right now, when I try posting something it comes up with an error saying
Failed to load resource: the server responded with a status of 422 (Unprocessable Entity).
When clicking on it in the console it opens a new tap where it just says
Cannot GET /api/list
Also in the command prompt, it says
Unhandled rejection Error: Can't set headers after they are sent.
Does anybody know why this might be and what I can do to fix it? Here are some snippets of my code:
Index.HTML:
fetch('/api/list', options)
.then(response => response.json())
.then(response => {
if (response.status == 'OK') {
console.log('song is added')
getList(items)
} else {
alert(response.message)
}
})
}
Server.js:
app.post('/api/list', userIsAuthenticated, (req, res) => {
let {
titleArtist
} = req.body
let user_id = req.session.user.id
// seaching for user id in database
let query = {
where: {
userId: user_id
}
}
It might also be somewhere else in the code it goes wrong. Let me know if I should post more snippets of code.
This is because you are making a GET request to POST API.
This is how you can make POST request
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

Fetch API body not working

It is a very simple fetch api but for some reason I dont know why the body is not working. here is the code.
<label id="msg"></label>
<label id="msg2"></label>
<script type="text/javascript">
const myRequest = new Request('some url', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({"email" : "email",
"password" : "password"}),
mode: 'no-cors'});
const myMethod = myRequest.method; // POST
const bodyUsed = myRequest.bodyUsed; // true
fetch(myRequest)
.then(response => {
if (response.status === 200) {
return response.json();
} else {
//throw new Error('Something went wrong on api server!');
}
})
.then(response => {
document.getElementById("msg").innerHTML = response;
document.getElementById("msg2").innerHTML = bodyUsed+" "+myMethod;
}).catch(error => {
document.getElementById("msg").innerHTML = error;
});
</script>
Is there anything I am doing wrong? I have stringify the body, changed the header but still when it runs, it shows false in msg2 label (which is nothing but just the body part of the request, just to be sure). which means the body is actually NaN. where is the problem and whats the solution?
mode: 'no-cors'
This means I do not want to do anything that would require the server to use CORS to grant permissions; do not throw CORS related errors.
Reading the response across origins requires the server grants permissions with CORS.
You said you weren't going to do that, so fetch does not try to make the body available to you.
(You are also prevented from doing anything that would require a preflight request, such as setting the Content-Type request header to JSON.)
Don't set the mode to no-cors.

Get Token From Api Dynamically To Access Content

I need to have the token to access the content like the announcement in my code. But what i do is to copy the token generated from loginUser() and paste it inside the getAnnouncement() under the fetch. I wrote Authorization : 'Bearer esuigiugeguigiguigi' <--- this is the token. The problem with this is that i need to copy and paste again the token every time it expires.
function loginUser(){
fetch('http://sample_website.com/api/auth/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: document.getElementById("email").value,
password: document.getElementById("password").value
})
})
.then(data => data.json() )
.then(data => {
if(data.response){
redirect: window.location.replace("../Sample/Home.html")
} else{
alert("Invalid Email or Password");
}
})
.catch((err) => {
console.error(err);
})
}
function getAnnouncement(){
fetch('http://sample_website.com/api/announcements', {
method: 'GET',
headers: {'Content-Type': 'application/json',
Authorization : 'Bearer esuigiugeguigiguigi'},
})
.then(data => data.json())
.then(data => { console.log(data)
const output = document.getElementById("display");
output.innerHTML = `<ul>
<li><h2>${data.data.data[0].title}</h2></li>
<li>${data.data.data[0].body}</li>
<li>Created: ${data.data.data[0].created_at}</li>
</ul>`;
})
.catch((err) => {
console.error(err);
})
}
Usually the response from an API call to get the token will hold:
the token
the duration of the toke
a link to refresh the token
One basic way of dealing with this is to keep the token data in localStorage or in memory or something (you can decide for yourself), and then just use it on any request that needs authorization.
It is possible that the API in question gives a specific error in case a token has expired. You can then catch it, use the link to refresh the token to get a new one, and repeat the request.
As there is not much info about the API in hand, or what you're doing and what (if any) framework you are using, this it the best answer I can provide at the moment. There are a lot of libraries out there handling this stuff already, so you might want to look into existing solutions as well.

Categories

Resources