React Post not showing Header - reactjs

Fixed:
I changed a few things in a go, so i can't really tell what solved my issue, but basically:
-the API needed int or long and i was sending String.. parseInt solved it.
I declared initially a data object:
const [data, setData] = useState({
})
With all the values i was gonna send later on(and with the correct data types! if i'm not sure, null seems to work pretty well for initialization).
-Another issue was that i merged all my data in a hook just before my POST request, since its asynchronous..it's a bad idea.
-Lastly, but most importantly, and that was probably the issue (thanks to EntiendoNull and JMadelaine), i initialized my data as [] and not as {}, so i was sending an object inside of an array.. hence the JSON parse error: Cannot deserialize instance of message in the API when i POST.
.----------------------------------------------------------------------------------------------------------------------------------.
I've got an issue with a post request not working properly.
Basically, the header is not right, it should be {"content-type": "application/json"}
But instead, it's an empty object.
Here is where i do the POST:
const [data, setData] = useState([]);
const createMission = async (e) => {
setData({
...data,
nom:state.missionName,
id_client:state.currentClientKey,
id_consultant:state.currentConsultantId,
id_manager:1,
id_ro:state.currentROKey,
id_rc:state.currentRCKey,
detail:state.missionDescription,
adresse:state.adresse,
frequence_eval:6,
date_debut:state.startDate,
date_fin:state.endDate,
metier:state.metier
});
let headers = {
headers: {'Content-Type': 'application/json'}
};
axios.post('http://localhost:8080/mission',data,{"headers" : headers})
.then(res => {
console.log(res);
});
Here is the content of the res on the console of my navigator:
{…}
​
config: Object { url: "http://localhost:8080/mission", method: "post", data: "{\"nom\":\"\",\"id_consultant\":null,\"id_manager\":1,\"detail\":\"\",\"adresse\":\"\",\"frequence_eval\":6,\"date_debut\":null,\"date_fin\":null,\"metier\":null}", … }
​
data: ""
​
headers: Object { }
​
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
​
status: 200
​
statusText: ""
​
<prototype>: Object { … }
The data is sent fine, I get a 200 status back, but as you can see, the headers have an empty object in it, and the data is an empty string "".
Funny thing is, I do almost the exact same thing on another component, and it works just fine :
In this case, I don't even specify the headers.
const createClient = async (e) => {
axios.post('http://localhost:8080/client', {nom:state.nomClient})
.then(res => {
console.log(res);
});
};
And here is the log :
{…}
​
config: Object { url: "http://localhost:8080/client", method: "post", data: "{\"nom\":\"aze\"}", … }
​
data: Object { id: 372, nom: "aze" }
​
headers: Object { "content-type": "application/json" }
​
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
​
status: 200
​
statusText: ""
​
<prototype>: Object { … }
The API is the same, it's a #RequestBody.
Here for the mission :
#PostMapping
public Mission addMission (#RequestBody MissionBean missionBean){
Optional<Client> optionalClient = clientRepository.findById(missionBean.id_client);
Optional<Consultant> optionalConsultant = consultantRepository.findById(missionBean.id_consultant);
Optional<Utilisateur> optionalManager = utilisateurRepository.findById(missionBean.id_manager);
Optional<Utilisateur> optionalRo = utilisateurRepository.findById(missionBean.id_ro);
Optional<Utilisateur> optionalRc = utilisateurRepository.findById(missionBean.id_rc);
if (optionalClient.isPresent() && optionalManager.isPresent() && optionalConsultant.isPresent() && optionalRo.isPresent() && optionalRc.isPresent()){
Mission newMission = new Mission(
missionBean.nom,
optionalClient.get(),
optionalConsultant.get(),
optionalManager.get(),
optionalRo.get(),
optionalRc.get(),
missionBean.detail,
missionBean.adresse,
missionBean.frequence_eval,
missionBean.date_debut,
missionBean.date_fin,
missionBean.metier
);
missionRepository.save(newMission);
return newMission;
}
return null;
}
and here for the client(2nd example that works just fine) :
#PostMapping
public Client addClient (#RequestBody Client client){
clientRepository.save(client);
Critere critere = new Critere(client,"Ponctualité",true);
Critere critere2 = new Critere(client,"Assiduité",true);
Critere critere3 = new Critere(client,"Intégration",true);
critereRepository.save(critere);
critereRepository.save(critere2);
critereRepository.save(critere3);
return client;
}
I've tried many different ways to specify the headers, but it still doesn't work.
The request works good(200), but the data is not being understood API side, no header, so an empty string as the data, I'm kind of new to this so I'm stuck here. When I check my Database nothing new has been added.
Edit:
I got a message from the API each time i make the request :
2020-02-22 22:19:39.737 WARN 4205 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `com.evalside.project.beans.MissionBean` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.evalside.project.beans.MissionBean` out of START_ARRAY token
at [Source: (PushbackInputStream); line: 1, column: 1]]
Maybe this can help pointing the issue
Edit2: Some of my values are supposed to be int but come as String(just noticed) Gonna fix that and try again

You probably do not want to use your state like that.
First, the initial value of your data state should be an object (according do what kind of type and value you point it to be later). Better be clear with your intentions from start :)
const [data, setData] = useState({});
Second, when updating a state the way you do may lead to problems.
Consider using setDate(prevState => { // your logic }) instead.
Third, from the code you are showing it does not make much sense to set your state the way you do and then feed it to your axios.post request. Or is there any other reason why those values are stored in a state before being used in your request? Most of them seem to already be stored in some other state already, right?
Instead, you could have declared a const holding those values:
const myData = {
nom:state.missionName,
id_client:state.currentClientKey,
id_consultant:state.currentConsultantId,
id_manager:1,
id_ro:state.currentROKey,
id_rc:state.currentRCKey,
detail:state.missionDescription,
adresse:state.adresse,
frequence_eval:6,
date_debut:state.startDate,
date_fin:state.endDate,
metier:state.metier
}
Typically once your side effect is done and you have received a response is when you may want to update a state like this one.
Fourth, you did declare a headers-object;
let headers = {
headers: {'Content-Type': 'application/json'}
};
So in your axios-request do this:
axios.post('http://localhost:8080/mission', data, headers);
instead of this:
axios.post('http://localhost:8080/mission',data,{"headers" : headers})

thanks for your help
First, the initial value of your data state should be an object (according do what kind of type and value you point it to be later). Better be clear with your intentions from start :)
const [data, setData] = useState({});
Actually it is, i wrote it like : const [data, setData] = useState([]); not with {}.
I'm starting to get into hooks, so yep i don't have the right habits yet, i'm gonna try to use setDate(prevState => { // your logic }) more often.
I have several components all lifting some values into this one, which will eventually make the post request, that's why it's a bit messy with all the states and the data passing by, but i've tried many ways, and i've already tried simply doing :
const data = {name:myName, date:myDate etc..}
(...)
axios.post('url', data, headers)
I have other things happening i missed in the API, gonna add it to the post, maybe it'll help ;)

Related

Django views not returning a value from a multiple parameter request?

I've been using vanilla Django as a backend to my React frontend. I'm trying to make a POST request using axios that passes a dictionary of 2 values to my django view, and so far on my front end the values are valid, the connection to the django url is made, but the only issue is the actual data being processed in the view. If I try to print the value, it returns as None. Heres what I have so far:
Relevant Code
views.py
def render_data(request):
reddit_url = request.POST.get('reddit_url')
sort = request.POST.get('sort')
print(reddit_url, sort)
users_data, count = run_data(reddit_url, sort)
data = {
'users_data': users_data,
'count': count,
}
return JsonResponse(data)
component.jsx
const APIcall = () => {
axios
.post(
`http://127.0.0.1:8000/reddit_data/`,
{
reddit_url: location.state.link,
sort: location.state.sort,
},
{
headers: {
"Content-Type": "application/json",
"X-CSRFToken": location.state.token,
},
withCredentials: true, //cors requests
}
)
.then((res) => {
console.log("YESSIR");
setLoading(false);
});
};
Expected/actual output
Ideally, the output would print the values from the request, but the actual result is just None, None.
What I tried
I tried using request.POST['reddit_url'] with no different results
Double checking the frontend values to make sure the POST call is going through with the correct values
I'll be honest I havent tried much I really cant understand this one
Turns out, my QueryDict was returning empty in my Django console while trying to print it, and I simply solved it by using var formData = new FormData(); appending my values, then using it as a parameter in my axios post to make a POST request.

How to post data when you have javascript object using multipart/form-data content-type

So I have never post a data using FormData and multipart/form-data as Content-Type in my React project. But now I'm kinda forced by backend to send it this way since we have some images in payload.
The problem is that the whole data is a JS object and can be parsed to JSON, and nothing more. So how can I convert my JS object into a valid FormData that backend would accept it? Everything works without a problem in Postman, but in the app I always get the same error.
Here is some more detail:
The working Postman sample:
What I expect to be working (but obviously doesn't):
const createProd = () =>
HttpRequest.post('/api/prod', {
body: {
Product: {
title: 'Test Prod',
shop: null,
description: "My new ad's description",
category: { id: '5d8c6aa6fadeaf26b0194667' },
condition: 'USED'
}
});
HttpRequest is a helper function which uses ES6 fetch for requests.
I always get the same error: "Required request part 'Product' is not present" with/without JSON.stringify.
I even tried to create a sample FormData to at least change the error:
cont payload = new FormData();
payload.append('Product', {foo: 'bar'});
But still same error. I also copied the code which is generated by Postman. But still no chance.
I would be thankful if you share your suggestions or workarounds.
Thanks in advance.
const formData = new FormData();
const product = { //your product object };
formData.append('product', JSON.stringify(product));
const config = {
headers: {
'Content-Type': 'multipart/form-data; charset=utf-8; boundary="another cool boundary";'
}
};
axios.post(`/api/ads`, formData, config).then((res) => {
console.log(res);
}).catch(err => {
console.log(err);
});
Maybe you should set header.
Try this one. In my case I used Axios. It worked for me in my project.

How to perform a post request with axios on React and pass your data as FormData?

There's this API:http://zssn-backend-example.herokuapp.com/api/, detailed here: http://zssn-backend-example.herokuapp.com/swagger-api/index.html#!/people/Api_People_index . I am trying to do a POST request on this endpoint "/people/{person_id}/properties/trade_item.json"(Make a trade transaction between survivors). On the Website for testing I filled the fields with the following data and got 204 response:
person_id:34e183a6-965e-4a61-8db5-5df9103f4d4b
consumer[name]: Person4
consumer[pick]: AK47:1;Campbell Soup:1
consumer[payment]: First Aid Pouch:2
I investigated a Little and got
this information
didn't understand the "PROPERTY[KEY]:VALUE" representation
When I try to the Request with this code, with the same values(by the way, the database of this API is cleared each 24 hours, so those value might not work, even if you do it in the right way):
this is My code:
async function handleTrade(e){
e.preventDefault();
const config = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
await api.post(
"/people/" + match.params.id + "/properties/trade_item.json",
{
person_id:match.params.id,
name: survivorRef.current,
pick: survivorItemsToPick,
payment: userItemsToPay,
},
config
);
And this is what I get:
Request:
request-description
Response:
response-description
How Can i make this request in the right way in order to get the same result as the first Image ?
You can use FormData to send the request, I made an example:
const data = new FormData();
data.append("customer[name]", "Person4");
data.append("customer[pick]", "AK47:1");
await api.post("/people/" + match.params.id + "/properties/trade_item.json", data, config)

Passing through an array with axios

I am having an issue passing through an array through axios post call. The issue is that on the api endpoint the data received is null, when I try posting using postman it works fine so the endpoint is working. Example of the array
I need to pass the data in this format:
{
"UpdateItemList": [
{
"Text": 1,
"Value": "5"
},
{
"Text": 1,
"Value": "5"
}
]
}
Code:
export function createLogEntry(postData) {
let payload = {
UpdateItemList: postData
};
const request = axios.post('https://localhost:44312/api/Audit/AddLogEntry', {
data: payload
});
return {
type: CREATE_LOG,
payload: request
}
}
Is there any issue with the way I am passing through the data with my current code?
Try with
const request = axios.post('https://localhost:44312/api/Audit/AddLogEntry',payload);
This worked for me!
The issue is that you are confusing two ways axios can be used. Currently you are actually posting your data nested in an object within and the key data:
{
data: {
UpdateItemList: postData
}
}
If you are using the axios.post function, you should just pass your object with the data to post as the second object like this:
const request = axios.post('https://localhost:44312/api/Audit/AddLogEntry', payload);
If you are using the config object method, you should just pass one single object with url, method and data as keys.
// Send a POST request
axios({
method: 'post',
url: 'https://localhost:44312/api/Audit/AddLogEntry',
data: payload
});
This behaviour is explained in the axios Readme here: https://github.com/axios/axios#axios-api

Modify Returned Response

I am trying to get a Session Key response to use in my future request inside a Zapier Session Authentication, however the response back from a successful authentication is "OK: hbsdakjdkaskjdfvbasdkjh". I need the hbsdakjdkaskjdfvbasdkjh extracted and then saved as the session key variable in the below zapier cli code
I am a little new to parsing JSON, but I think the response is actually raw... I tried a Regex but couldn't figure out the right statement and wondered if someone could help point me in the right direction.
The session URL params etc are working, and the Session Key responding after the OK: is actually correct and one I can use for the remainder of the session manually....
const options = {
url: 'https://theconsole.domain.com.au/api/auth.pl',
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded',
'accept': 'application/json'
},
params: {
'AccountNo': bundle.authData.AccountNo,
'UserId': bundle.authData.UserId,
'Password': bundle.authData.Password
},
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content);
// You can do any parsing you need for results here before returning them
return {
'sessionKey': results.sessionKey
};
});
Cool, so if your response is not json, you'll want to remove the z.JSON.parse line, since that'll throw an error.
As for pulling the key out of the response, success will depend on knowing that the response will always have a certain format. In this case, it sounds like it's OK: somekey.
If we can safely assume that there'll only ever be one space () and it's directly before the key, you can try something like:
// the rest of the code
respone.throwForStatus(); // important, assuming the server gives a non-2xx code for a bad auth
const sessionKey = response.content.split(' ')[1];
return {sessionKey}; // shorthand for {sessionKey: sessionKey}
Assuming those assumptions hold true, that should work!

Resources