what is this error after submit formData in reactjs - 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

Related

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

Type error : getting failed to fetch React js

this is my code for API postman, but i keep getting errors typeError: failed to fetch
i've looked the code bunch of times but i cant find the issue
async function signUp() {
let item= {username,email,password}
console.warn(item)
// calling api
let result = await fetch("myApiLink",{
method:'POST',
body:JSON.stringify(item),
headers:{
"Content-Type": 'application/json',
"Accept" : 'application/json'
}
})
//resolve json
result = await result.json()
localStorage.setItem("user-info",JSON.stringify(result))
navigate('/add')

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

Camunda: How to deploy a process using ReactJS fetch

I am trying to use Camunda's REST api to deploy a new process. However, I keep getting this HTTP response when my function is called.
Response:
{"type":"InvalidRequestException","message":"No deployment resources contained in the form upload."}
My jsx function
async deployNewProcess(xmlData) {
const formData = new FormData()
const blob = new Blob([xmlData], {type:'application/octet-stream'})
formData.append('upload', blob)
const response = await fetch(`${baseurl}/deployment/create`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data; boundary=<calculated when request is sent>',
'Content-Length': '<calculated when request is sent>',
'Host': '<calculated when request is sent>'
},
body: formData
})
.then(result => console.log("SUCCESS: ", result))
.catch(err => console.log("ERROR: ", err))
}
Has anyone had any experience with this?
Based on this post https://camunda.com/blog/2018/02/custom-tasklist-examples/
see the example code
here:
https://github.com/camunda-consulting/code/blob/b2c6c3892d3d8130c0951a1d3584be7969fec82a/snippets/camunda-tasklist-examples/camunda-react-app/src/middleware/api.js#L11
and here:
https://github.com/camunda-consulting/code/blob/b2c6c3892d3d8130c0951a1d3584be7969fec82a/snippets/camunda-tasklist-examples/camunda-react-app/src/actions/camunda-rest/deployment.js#L4

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

Resources