json server fake rest api with POST - reactjs

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("/");
});

Related

Send data on a JSON server using react

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

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

Fetching an API in react

I am new to React, And I am Stuck. I am trying to make a signup page, having textboxes: name,phonumber,email,password.
What I want is, When I click on login button, all these details should be sent over POST to my API, and response is fetched and stored.
API:
http://localhost:5000/api/users/signup
Method:
POST
Request to my api is send in this way:
content-type: application/json
{
"name": "Devanshh Shrivastvaaaa",
"phoneNumber":"982964XXX8",
"email": "devannnnnshh;#ccc.in",
"password": "1234566788"
}
Can anyone please explain me using code how to send this data to my api on clicking signup, and fetching response
Don't need to use any third party libraries, just use the Javascript fetch API
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
Source: Mozilla MDN
you need to install axios or fetch axios is good axios
axios.post('http://localhost:5000/api/users/signup', {
name: "Devanshh Shrivastvaaaa",
phoneNumber":"982964XXX8",
email: "devannnnnshh;#ccc.in",
password: "1234566788"
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
also check for further

Can't access the data returned by api call to http://dummy.restapiexample.com/api/v1/employee/3

I`m trying to model an application for managing the employees of a company. My problem: I'm trying to fetch the data of a specific user, calling the API endpoint : http://dummy.restapiexample.com/api/v1/employee/3 (the 3 can be replaced by other user-ids).
When I'm calling the endpoint from Postman I get this response
But when I try to access the same resource from my React application I get this response.
Here is how I call the API endpoint
export async function getSingleEmployee() {
return fetch('http://dummy.restapiexample.com/api/v1/employee/3', {
mode: 'cors',
method: 'GET',
dataType: 'json',
headers: {
'Access-Control-Allow-Origin':'*',
'Content-type': 'application/json;charset=utf-8',
}
})
.then(response => response)
.then(data => {
console.log(data);
})}
How can I access the data as I do in the Postman request? What am I missing?
Did you try using "await" fetch.... ?

Receive JSON content of Fetch API Post call

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

Resources