Spotify API token request - 400 `SyntaxError: Unexpected End of Input` - reactjs

I'm working on a Next.js web app that needs to connect with the Spotify API. I successfully got the authorization_code, but I am getting a 400 error on the api/token endpoint.
I have already tried replacing body with params and data in the fetch call. I have also tried parsing the JSON into a const before passing it to fetch.
try {
const res = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${process.env.SPOTIFY_CREDS_BASE_SIXTYFOUR}`,
},
body: JSON.stringify({
grant_type: 'authorization_code',
code: authCode,
redirect_uri: process.env.SPOTIFY_REDIRECT_URI,
client_id: process.env.SPOTIFY_CLIENT_ID,
client_secret: process.env.SPOTIFY_CLIENT_SECRET,
}),
});
const data = await res.json();
dispatch({ type: GET_NEW_ACCESS_TOKEN_SUCCESS });
} catch (error) {
console.error('getNewTokens() ERROR', error);
dispatch({ type: GET_NEW_ACCESS_TOKEN_FAILURE });
}
I expect to receive the access tokens, but instead I am seeing:
VM538:1 POST https://accounts.spotify.com/api/token 400 (Bad Request)
and
getNewTokens() ERROR SyntaxError: Unexpected end of input
at _callee$ (AuthActions.js:37)
at tryCatch (runtime.js:45)
at Generator.invoke [as _invoke] (runtime.js:271)
at Generator.prototype.<computed> [as next] (runtime.js:97)
at asyncGeneratorStep (asyncToGenerator.js:5)
at _next (asyncToGenerator.js:27)

You can try update your header like below, as you are passing JSON on your body
headers: {
'Accept': 'application/x-www-form-urlencoded; application/json',
Authorization: `Basic ${process.env.SPOTIFY_CREDS_BASE_SIXTYFOUR}`,
}
Updated your header to accept JSON format also
I tried to update your request and further updating this header am able to post my body as expected. As i don't have credentials i am receiving 500, but my request reached server.

I think the problem could be due to JSON.stringify. please try content type application/json

I was unable to successfully complete the request using the fetch library, but using the request library with the same headers worked successfully.
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: SPOTIFY_REDIRECT_URI,
grant_type: 'authorization_code',
client_id: SPOTIFY_CLIENT_ID,
client_secret: SPOTIFY_CLIENT_SECRET,
},
json: true
};
request.post(authOptions, (error, response, body) => {
if (!error && response.statusCode === 200) {
// Success
} else {
// Failure
}
});

Related

when I adding a note in my todo list app i am getting error in console i think the problem is in react

I'm using axios in a React App. This is the code where I make the API call. It throws an error in the console: Uncaught (in promise) Failed to fetch
const response = await fetch(`${host}/api/notes/updatenote/${id}`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"auth-token": "auth-token"
},
body: JSON.stringify({title, description, tag})
});
const json = response.json();
How can I fix this?

CORS error while trying to post data with Axios on AWS REST API configuration using a node.js Lambda function

I'm posting data to a DynamoDB table with axios in a React front-end.
The API is set up through a serverless configuration with an API Gateway and Lambda on AWS.
While the request goes through and I see the added item on the database I still get a CORS error https://i.stack.imgur.com/m7yMG.jpg
This is the axios method:
import axios from "axios";
export const sendItemToDB = async (_data) => {
if (!_data) { return };
try {
const res = await axios({
method: "POST",
url: process.env.REACT_APP_QUERY_API,
data: _data,
headers: {
"Content-Type": "text/plain"
},
});
console.log("data returned from api", res);
} catch (error) {
console.log("Error sending File to db: ");
console.log(error);
}
};
And the API method on Lambda:
const createRecord = async (event) => {
const response = { statusCode: 200 };
try {
const body = JSON.parse(event.body);
const params = {
TableName: process.env.DYNAMODB_TABLE_NAME,
Item: marshall(body || {}),
};
const createResult = await db.send(new PutItemCommand(params));
response.body = JSON.stringify({
message: "Successfully created record.",
createResult,
});
} catch (e) {
console.error(e);
response.statusCode = 500;
response.body = JSON.stringify({
message: "Failed to create record.",
errorMsg: e.message,
errorStack: e.stack,
});
}
return response;
};
I based this configuration on this tutorial : https://github.com/jacksonyuan-yt/dynamodb-crud-api-gateway
I solved this following amazon documentation and reconfiguring the serveless deployment yml.
Serverless documentation on api gateway and lambda proxy integration here
Adding the missing headers to all lambda functions was essential.
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
};
Also testing that OPTIONS is working for the preflight:
https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-test-cors.html
Just as Stavros noticed, the problem is that this is not a simple cross-origin POST method request (because it contains custom headers), so you need to tweak CORS settings of AWS API Gateway by adding
"POST, GET & OPTIONS" for Access-Control-Allow-Methods
"content-type" for Access-Control-Allow-Headers
You can do it through console like this
You also might need to add those headers in lambda like this
and it will work.

Unable to access a POST endpoint's reponse body as json

When trying to get a dummy response from a POST endpoint, the call to res.json() throws a serialization error in the client:
Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
This is the client side:
const body = /* request body */
const res = await fetch(/* url */, {
method: 'POST',
body: JSON.stringify(body),
})
console.log(await res.json())
And this is the endpoint:
export const POST = async ({request}) => {
/* do something with the request's body */
return {
body: {a: 1}
}
}
I get the same error on the server side if I don't stringify the body in fetch, but I can't stringify it in the endpoint, as only plain objets (and errors) are allowed.
The outcome is the same with an empty object.
You have to instruct the endpoint to send JSON, otherwise it will send the associated page as server-side rendered HTML. To do that add an Accept header:
const res = await fetch(/* url */, {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: JSON.stringify(body),
})

what is this error after submit formData in reactjs

when i'm sending image with text data than showing this Error:
VM83:1 Uncaught (in promise) SyntaxError: Unexpected token '<', "<br />
<b>"... is not valid JSON
here is my code :
async function handleSubmit(e) {
e.preventDefault();
// console.log(pname,pimg,pdesc)
let formdata = new FormData()
formdata.append('pname', pname)
formdata.append('pimg', pimg)
formdata.append('pdesc', pdesc)
console.log(formdata)
const result = await fetch("http://localhost/ecomapi/addProduct.php", {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
},
body:formdata
})
result = await result.json();
console.log(result)
}
i'm trying to insert data with api .
The data returned from the api is not well-formed json, so when you attempt to parse it as a json object with:
result = await result.json();
...it throws an error.
Log the return from the api directly and use an online json validator like: https://jsonlint.com/ to see where the error is in greater detail.
Read about .json() and streams: https://developer.mozilla.org/en-US/docs/Web/API/Response/json
Remove headers or in headers Content-Type
headers: {
'Accept': 'application/json'
}
without headers you can submit form data. and also check your api page may be have there sql problem

VM1710:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

I am trying to get an access token from the server-side with JWT using the post method. So I passed the user's email to the server-side to verify from the server-side while the user is login.
I am getting this two error
useToken.js:14 POST http://localhost:5000/token 400 (Bad Request)
VM1710:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Server-side:
app.post("/token", (req, res) => {
const user = req.body;
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: "1d",
});
console.log(accessToken);
res.send(accessToken);
});
Client-side:
fetch("http://localhost:5000/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(email),
})
.then((res) => res.json())
.then((data) => {
setToken(data);
localStorage.setItem("accessToken", data);
});
NOTE: Other APIs on the server-side are functional while these errors occur.

Resources