React / Strapi - API request put data in the CMS - reactjs

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

Related

React SPA: the best way to store auth token?

I know this question has been asked many times but there is no clear answer so far and the suggested options (cookies, local storage etc..) have all pros and cons. I'm new to React SPA and I'm very confused about the right method to adopt.
For now I've based my application on the "cookie-to-header token" premise.
The API I work with returns a token meant to be used with the Authorization header for the POST PUT and DELETE requests.
So on the login page a cookie is created in order to store the token value:
const login = { email, password };
const [error, setError] = useState(null);
fetch('https://apidomain.net/api/login', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(login)
}).then((res) => {
if (!res.ok) {
throw Error('Could not fetch the data for this resource. Status: '+res.status+' Message: '+res.statusText);
}
return res.json();
})
.then((data) => {
document.cookie = "auth_token="+data.auth_token;
}).catch((err) => {
setError(err.message);
});
Then, the token value is retrieved by Javascript whenever a POST PUT or DELETE request is sent:
fetch('https://apidomain.net/api/post/4', {
method: 'DELETE',
headers: { 'Authorization': 'Bearer '+getAuthToken()}
})
It works fine but is it safe ?
Is there a better way to do that ?

json server fake rest api with POST

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

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

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