I want to send a large json object through a POST request - javascript

I am using a the fetch api to send a post request to my NodeJS/Express/MongoDB based API but somehow, only some of the fields are posted to the MongoDB collection. The rest are omitted. When I use console.log to print the whole js object in the console, I get a partial object with a ... at the end, which when hovered over, shows "Value below was evaluated just now". Looks like the request is sending the object in chunks. I want to send the whole object. How can I send the whole object?
FRONTEND:
document.getElementById('contact-submit').onclick = async (e) => {
e.preventDefault();
console.log(postData('http://localhost:4001/people',{
"name":document.getElementById('name').value.toString(),
"age": document.getElementById('age').value ,
"sex":document.getElementById('sex').value,
"address":document.getElementById('address').value,
"class": document.getElementById('class').value,
"degree": Number(document.getElementById('degree').value),
"grade":document.getElementById('grade').value,
"notes":Date(document.getElementById('notes').value),
"resume":Number(document.getElementById('resume').value),
"skills":criteria,
"rounds":rounds,
}));
}
async function postData(url = '', data ={}){
console.log(data);
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers:{
'Content-Type': 'application/json',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(data)
});
return response.json();
}
The object comes from a form, and only a part of it gets posted in the api.
PS. The API on its own works fine and POSTs complete objects when operated on through postman.

Related

Fetch returns unathorized and undefined

I'm trying to access to an API using fetch however the error I receive in console:
XHR GET https://api.geoapify.com/v1/geocode/search?street=buenos%20aires&city=barcelona&country=espa%C3%B1a&lang=es&limit=1&format=json&apiKey=hereIputmyrealkey
Estado 401 Unauthorized
Versión HTTP/2
Transferido1,52 KB (tamaño 97 B)
Política de referenciastrict-origin-when-cross-origin
The fetch looks like this:
var requestOptions = {
method: 'GET',
credentials: "include"
};
let response = await fetch("https://api.geoapify.com/v1/geocode/search?street=buenos aires&city=barcelona&country=españa&lang=es&limit=1&format=json&apiKey=${MYKEY}");
When I add:
.then(error => console.log(error)
It return response undefined.
I'm working on cakephp, the url for the fetch works and outside of cakephp the fetch works too. Do I need to add something to the fetch?
(The key in my code is my actual key and the url gives a response in json format).
I tried adding:
var requestOptions = {
method: 'GET',
credentials: "include"
};
and
var requestOptions = {
method: 'GET',
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
but it gives the same error...
Use back ticks when adding ${variable}
let response = await fetch(`https://api.geoapify.com/v1/geocode/search?street=buenos aires&city=barcelona&country=españa&lang=es&limit=1&format=json&apiKey=${MYKEY}`);

Javascript: multiple fetches

I have the following problem. I have a server who implemented his own authentication process. For that they take the credentials as body.
async function authenticate(){
var cred = JSON.stringify({
"email": "user#test.de",
"password": "1234"
});
const response = await fetch("http://.../rest/auth/login", {
method: 'POST',
mode: 'cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: cred
})
}
The response has the code 200 and says "login successfull!" and has a SET-COOKIE header has
the session cookie.
Now I've a second request with which I load the actual data. But when I try this and I get the response code 401: Unauthorized.
async function getData(){
const now = new Date()
const response = await fetch(`http://.../rest/....`)
console.log(response)
const data = await JSON.parse(response)
console.log(data)
}
authenticate()
.then((res) => {
console.log(res)
getData().then(reso => console.log(reso))
})
Im not sure how to handle this problem.
I've already checked all responses and everything worked except that the second request doesnt use the Cookie in their request. I've also tried to use the WithCredentials=true option but without success.
EDIT
I changed the credentials from
credentials: 'cross-origin' -> credentials: 'include'
Since im calling an extern Server from localhost.
But i get still an 401 Error.

Not receiving data on server when doing an API POST call from the client

Already checked the endpoint with Insomnia and is working fine, but when trying to connect with the backend from the client there is some kind of problem. The connection between the client and the server is done this way:
const uri = `${basePath}/${baseVersion}/sign-up`;
const params = {
method: "POST",
body: JSON.stringify(data),
header: {
"Content-Type": "application/json"
}
};
And if I show in the console params object this is what is inside it:
enter image description here
Just to clarify, there isn't a CORS problem as I am using a Google Chrome extension for it.
This is the response of the fecth:
enter image description here
Is your problem not receiving a response from the server in the promise? If so, that is because there is no code in your snippet that actually returns the data. (Sorry if I misidentified the problem, I don't have the ability to comment)
const uri = `${basePath}/${baseVersion}/sign-up`;
async function fetchPost(data = {}) {
var response = await fetch(uri,
method: "POST",
mode: "cors",
header: {
"Content-Type": "application/json"
},
referrerPolicy: "strict-origin-when-cross-origin" //you can replace that with anything you want depending on the situation
body: JSON.stringify(data)
});
// if you're expecting the response to be json, use the below, but if you want it in text, then do response.text, etc.
return response.json();
}
fetchPost();

Sending GET data via fetch() in body instead of specifying it in the URL

I am trying to convert this jQuery call to native Javascript using fetch() as mentioned in MDN (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_request_options).
$.ajax(
{
method: "GET",
url: CB_ABS_URI + "ajax/get-checkin.php",
dataType: "json",
data: { DwellingUnitID:DwellingUnitID },
})
to
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'GET', // *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, *client
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return await response.json(); // parses JSON response into native JavaScript objects
}
postData(CB_ABS_URI + "ajax/get-checkin.php", { DwellingUnitID: DwellingUnitID })
.then((data) => {
console.log(data); // JSON data parsed by `response.json()` call
});
But I can't seem to send GET data in the body. Is adding the query to ajax/get-checkin.php the only way ?
But I can't seem to send GET data in the body
fetch makes a clear distinction between the query string in the URL and the data in the request body (unlike jQuery which switches between them depending on the request method).
Is adding the query to ajax/get-checkin.php the only way ?
Yes, see the documentation:
If you want to work with URL query parameters:
var url = new URL("https://geo.example.org/api"),
params = {lat:35.696233, long:139.570431}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)

How to Upload Images using React, fetch, and Django REST

I'm encountering a bit of a roadblock in my dev work. I'm trying to upload a photo that I'm sending using FormData in fetch. I'm guessing my problem is in my content header or my back-end handling. Eitherway, I can't seem to find a way around it. I hope you guys can help me
general.js - this is my handler for a request
export const postDataWithImage = (url, data) => {
return fetch(url, {
body: data, // must match 'Content-Type' header
credentials: 'same-origin', //pass cookies, for authentication
method: 'POST',
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
})
.then(response => response.json()); // parses response to JSON
};
user-creation.js - my actual usage of the function above (sending multiple data)
heres an image of the data I'm sending
![1] https://imgur.com/leBlC7L
const data = {...this.state, ...form};
const formData = new FormData();
Object.entries(data).forEach(([key, value]) => formData.append(key, value));
postDataWithImage('/users', data)
.then(data => {
if (data.error) {
console.log("theres an error");
this.setState({
error: data["error"]
});
console.log(this.state.error);
} else {
console.log(data["data"]);
}
})
.catch(error => message.warning(error.message));
views.py - my backend handler using Django REST not: this returns me an error either byte has no attribute 'get'... or an empty ModelDict for request.FILES
#staticmethod
def post(request):
print(request.body.get('image'))
print(request.FILES)
if "username" not in request.data or "password" not in request.data:
return Response(data={
"error": "Missing username or password"
}, status=400, content_type="application/json")
return Response(data=data, status=200, content_type="application/json")
Please help me I'm really stuck. Thank you!
I faced similar problem using Vue.js and Django.
Finally I noticed that the problem was that: boundary was not set to the header.
The solution is to remove headers from your request like this:
fetch(url, {
body: data, // assume this is some binary data
method: 'POST',
})
Then, your browser will automatically add proper headers for your request. And you will see boundary field which is added by your browser in your request headers.
Try to remove the "Content-Type" from the headers of fetch

Categories