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

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),
})

Related

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

React / Strapi - API request put data in the CMS

Quick question: I made a API fetch function for my Strapi CMS but can't seem to get the right JSON.
This results in my API call adding a new item within the Strapi CMS (200 OK HTTP). But without the provided data. I'm guessing that the JSON is wrongly formatted and the data gets lost.
What works:
Authorization works
API request works (200)
There is an empty article within the Strapi CMS
What doesn't work:
Data doesn't get set within the CMS.
The code:
// POST request using fetch with error handling
function setArticle() {
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${state.jwt}`
},
body: JSON.stringify({
slug: "first-success",
name: "First successful API request"
})
};
fetch('http://localhost:1337/articles', requestOptions)
.then(async response => {
const data = await response.json();
console.log(requestOptions);
// check for error response
if (!response.ok) {
// get error message from body or default to response status
const error = (data && data.message) || response.status;
return Promise.reject(error);
}
this.setState({ postId: data.id })
})
.catch(error => {
console.error('There was an error!');
});
}
What I tried, logging and reading the Strapi documentation.
The problem was, case sensitivity. Apparently when making a new content type within Strapi I set the entity with an uppercase. (Slug and Name) resulting to my body within my HTTP request getting ignore.
I changed the Strapi fields without an uppercase and it's now working.
body: JSON.stringify({
slug: "first-success",
name: "First successful API request"
})

Problems using uri on axios

I currently work with an api rest where I pass the controller parameters, version and action via URI. However, when I execute a request with URI with more than 19 characters, it gives this CORS error:
Access to XMLHttpRequest at 'http://my-api-host/toll/vehicle/v1/list' from origin 'http://localhost: 3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
In authentication the request works even with URI having more than 19 characters. However, any other request with a different URI that has more than 19 characters gives this same error. I use my application's API and the request works normally.
I'm using axios in Reactjs.
The api is already configuring to accept the content-type I am using (application / json) and is also already accepting requests from different sources.
My request code:
request(uri, params = {}){
return new Promise((resolve, reject) => {
axios
.post('http://my-api-host' + uri, JSON.stringify(params), {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (response.data.success) {
resolve(response.data);
} else {
reject(response.data);
}
});
});
};
Has anyone been through this and could help? thanks in advance
Did you use Fetch instead?
async function postData(url = '', params = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
headers: {
'Content-Type': 'application/json'
},
qs: JSON.stringify(params) // query string data
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('http://my-api-host', params)
.then(data => {
console.log(data);
});

Unable to send request.data and get api response?

Requesting with Axios to fetch data from API
export const getReports = async (url, obj) => {
return new Promise(
async (resolve, reject) => {
try {
const data = await axios.request(
{
method: 'get',
url: BASE_URL+url,
headers: {
'Authorization': `Bearer ${await getAccessToken()}`
},
data: {date_to:'2019-11-05',date_from:'2019-11-05',c_name:'1'}
}
);
resolve(data);
} catch (e) {
reject(e)
}
}
)
};
Getting error and not able to receive request.data on the backend...
Working on Postman
in Body
- date_to:'2019-11-05'
-date_from:'2019-11-05'
-c_name:'1'
If you have request type of GET axios doesn't use the data field.
(From the docs)
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
data: {
firstName: 'Fred'
},
The data field is for POST, PUT, PATCH, etc. You could try using query params or change the type of the request.
Here is about query params from the docs
// `params` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
params: {
ID: 12345
}
So this would appear as url.com?ID=12345
Then you can parse them from the backend. This is also the HTTP standard and you shouldn't try sending body data with GET request.

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

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
}
});

Resources