am trying to send a post request to a JSON server using react. I've captured the data from a form using react formik. When I try to make a post request, the server only creates an id but the rest of the data is not captured. I've tried logging out the data just before the fetch method and it appears. It's only the server that is not picking it.
Below is the submit method from formik.
const onSubmit = (values) => {
console.log(values)
fetch('http://127.0.0.1:8000/contacts/', {
method: 'POST',
body: JSON.stringify(values),
headers: {"Contect-Type": "application/json; charset=UTF-8"}
}).then(responce => {
if (!responce.ok) {
alert("Failed to add")
}else{
alert("Contact added")
}
return responce.json();
}).then(data => {
console.log('Added')
})
}
Related
I have captured an image with React Native (expo-app) and can't find a proper way to send it to backend, mostly 500 and 422 appears (422 at this example).
Here is how a image data looks
{"base64": null, "height": 820, "uri": "file:///var/mobile/Containers/Data/Application/792E2665-5063-4853-876E-3793568C7FCF/Library/Caches/ExponentExperienceData/%2540anonymous%252Fexpo-app-27783a0c-0a97-44a6-be26-48d37639bb25/ImageManipulator/9FCEF372-7C90-484F-9028-7D4271F9978D.jpg", "width": 476}
Here is the axios request to the backend, a photo state contains the data of image like above
const handleSubmit = async() => {
const formData = new FormData();
formData.append("photo", {
uri: photo.uri,
name: photo.uri.split('/').pop(),
type: 'image/jpg'
});
await axios.post("/api/upload", {
formData
}, {
headers: { "Content-Type": "multipart/form-data" },
}).then(response => {
console.log(response.data)
})
}
Here is the laravel side, it can't go through validation
public function store(Request $request)
{
$validated = $request->validate([
'photo' => 'required|mimes:jpg,png,jpeg'
]);
return response()->json([
'status' => 'successfuly executed',
]);
}
Here is the laravel err log of what was in the request, even though console logging in the front end right before sending request, an object of image exist.
{"formData": null}
I can't figure out how to upload or even get captured image to react back-end, any ideas?
await axios.post("/api/upload",
formData
, {
headers: { "Content-Type": "multipart/form-data" },
}).then(response => {
console.log(response.data)
})
remove brackets and try again
This image URI - file:///var/mobile/Containers/Data/Application/792E2665-5063-4853-876E-3793568C7FCF/Library/Caches/ExponentExperienceData/%2540anonymous%252Fexpo-app-27783a0c-0a97-44a6-be26-48d37639bb25/ImageManipulator/9FCEF372-7C90-484F-9028-7D4271F9978D.jpg is a reference to image data on device memory but not actually image data.
expo-image-picker returns base64 image data and you can upload them to your server.
I am using JSON server fake rest API and having issues with POST method. When I use to submit the form, the data should be added to the API. In the console.log it shows the data so it means that the promise has been executed but that data is not added to API. Following is the POST method i am using:
fetch("https://my-json-server.typicode.com/<github_id>/<github_repo>/blogs/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(blog),
}).then(() => {
console.log("blog added");
console.log(blog);
setTitle("");
setBody("");
setAuthor("adam");
setIsLoading(false);
history.push("/");
});
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"
})
I am trying to send a post request from my React front end to my Express front end, for some reason, the object I want to recieve, is being displayed so that the object is the key of another object and the value is and empty string.
Here is my onSubmit React function
handleSubmit = event => {
event.preventDefault()
const backend = '/api/login'
fetch(backend, {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: JSON.stringify(this.state)
})
.then(res => {
res.json()
})
.then(user => {
console.log(user)
})
.catch(err => {
console.log(err)
})
}`
And my post function on the express server
app.post("/login", (req, res) => {
console.log(req.body)
})
For example, if the object I want to send is {username: "user1", password: "password"}, when I console.log(req.body), I get { '{"username":"user1","password":"password"}': '' } in the console.
How do i fix this so i get the object that I requested?
Because it is JSON format. To parse it you can use:
JSON.parse('{"username":"user1","password":"password"}')
or JSON.parse(req.body)
The approach is fine with JSON.stringify() because it should be posted just like a string to the server. But if you want it to be an object at the backend then you have to parse it back with:
const userObj = JSON.parse(req.body.Data); // it will parse it back as an object
I am new to React and I have a chat UI in which I am trying to test an API call from a service.
Please assume that the call itself have the correct parameters, and even if not I want to see the error JSON response and I am just getting a blank message in the chat as a response to the user message.
The call working through Postman app in chrome but when trying to assign the call result to var in react it doesn't present the JSON response value when trying to post the message through the UI chat.
This is the function, the user message transfered to this function and then an answer should appear right after via the fetched API request:
submitMessage(e) {
e.preventDefault();
var s = fetch('https://***', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': '****',
},
body: JSON.stringify({ inputText: 'hi' })
});
this.setState({
chats: this.state.chats.concat([
{
username: "newUser",
content: <p>{ReactDOM.findDOMNode(this.refs.msg).value}</p>
},
{
username: "responsePlace",
content: s
}
])
});
}
fetch is a javascript Promise therefore it needs to be resolved using then
fetch(...)
.then(response => response.json()) // resolves json content of the response
.then(data => console.log(data)) // your actual data as a javascript object
.catch(ex => console.log(ex)) // exception handler in case anything goes wrong in the fetch
More on fetch api: fetch api examples
More on Promises: Promises