I'm trying to send a Delete request using Fetch. I get a response status - OK, but data is null. However the request has a body with an object, but I'm unable to see it back in the data received from the request. Here is a sample code.
let myObj = {
test: test1
}
fetch(deleteUrl, {
method: 'DELETE',
headers: {
"Content-type": "application/json;charset=UTF-8"
},
body: JSON.stringify(myObj)
}).then(
response => response.json()
).then(function(data) {
console.log(data) // Here the data is always null, but I want to log the request body(myObj)
})
From my limited understanding of "fetch", you seem to looking at the response data, not the request data.
Related
I am calling a Cron Job and work fine, but I have an application need to call the Cron Job, my app use the URL and my app start the cron job but I want to get the JSON RESPONSE to record the final status, like this
{"status":403,"message":"Export #23 is currently in manually process. Request skipped."}
This is the response in the browser its a simple JSON but I can't get the result, this is the code
function Export() {
var uri = "https://originalURL.com/wp-load.php?export_key=s4DdYEDQ4DOC2222&export_id=23&action=trigger"
fetch(uri, {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
}).then(response => response.json())
.then(data => {
alert(data.message);
}).catch(err => alert(err))
}
The cron start OK but i need to get the response to record a historial in my database !
You can make a call to a file that saves the response in a database or text file on the server-side. An example of this would be
getData.html
<html>
<body>
<script>
var response = {"This is my response key":"This is my response value", "This is another key":"This is another value"};
$.get("saveData.php", {response: response});
</script>
</body>
</html>
saveData.php
<?php
$response = $_GET['response'];
file_put_contents('responseText.txt',$response);
?>
Here, getData.html gets the response data (from the variable response), sends a request to saveData.php with the response data, and saveData.php puts the response into responseText.txt, which you can later extract from.
I'd like to pass a null value in a fetch POST request.
To illustrate this example, here is a screenshot from my API client, Insomnia (equivalent to Postman).
This POST in insomnia returns the desired results.
Now I try to do it in javascript using the following code:
let decal_colo = document.querySelector('#decal_colo').value.trim();
if (!decal_colo) {decal_colo=null};
let owner = document.querySelector('#owner').value.trim();
console.log(decal_colo, owner)
const response = await fetch('/api/testFilter', {
method: 'POST',
body: JSON.stringify({ decal_colo, owner }),
headers: { 'Content-Type': 'application/json' },
});
if (response.ok) {
const filteredData = await response.json();
console.log(filteredData);
You can see I am attempting to pass the null value in this line if the user does not give any input:
if (!decal_colo) {decal_colo=null};
This will console.log a value of null but my API route is not interpreting this in the same way. There is no error, but zero results are returned. I have looked at the database and there should be some results returned.
If it is helpful, I am using sequelize to create my Model and Controllers
How can I pass null in the correct way?
In the Insomnia app you are sending a JSON object but in the JavaScript code you are sending a string. Replace the body: JSON.Stringify with this:
body: { decal_colo, owner }
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();
I am calling the GET method using cross-fetch. The problem that I encounter is that I receive the response with code 200 but the body is empty. When I go to the console of the browser and open a Network tab I can see the result:
as you can see in the image there is a data in the response. The code that is responsible for hitting the API looks like this:
fetch(API_URL + 'load_packages', {
method: 'GET',
headers: {
Accept: 'application/json',
}
}).then((response) => {
console.log('LOAD PACKAGES RESPONSE: ' + JSON.stringify(response))
proceedLoadResponse(response)
})
The call works because I receive the response with the status code 200, but there is no body. What am I doing wrong?
UPDATE
Using of the response.json() returns {}
According to fetch documentation you have to covert response in json form by using response.json() to get actual body.
fetch(API_URL + 'load_packages', {
method: 'GET',
headers: {
Accept: 'application/json',
}
}).then(function(response) {
return response.json();
})
.then((response) => {
console.log('LOAD PACKAGES RESPONSE: ' + JSON.stringify(response))
proceedLoadResponse(response)
})
response is the Response object, which is just a container object that represents the response. Assuming that cross-fetch is just a platform-independent implementation of the native fetch, to retrieve the JSON from the response, you need to use the response.json() method.
I have been using ajax to get back some json data and recently tried using the fetch implementation.
I am having different responses, my ajax returns a string with all my key/value pairs, while the fetch query is returning response objects which do not at all contain any of my key/value pairs. (I am requesting the exact same resource in both examples and receiving different responses)
Could anyone let me know what Im doing wrong or why this is happening?
ajax request:
$.ajax({
url: "/" + name + ".json",
dataType: "text",
success: function (data) {
console.log(data);
var json = $.parseJSON(data);
var itemArray = [];
$.each(json, function() {
itemArray.push( { value: this.id, label: this.name } );
});
//Populate the List
populateListBox(name, itemArray);
}
});
console log result: (this is the response I want to be getting using the fetch method)
[{"id":1,"name":"two on two","abbreviation":"2v2","inhouse":true,"length":50,"capacity":1,"price":"50.2","salary":"15.22","url":"http://localhost:3000/en/products/1.json"},{"id":2,"name":"threesome Lessons","abbreviation":"3SUM","inhouse":false,"length":50,"capacity":3,"price":"33.33","salary":"11.11","url":"http://localhost:3000/en/products/2.json"},{"id":3,"name":"Prod1","abbreviation":"PRR1","inhouse":true,"length":22,"capacity":2,"price":"20.0","salary":"20.0","url":"http://localhost:3000/en/products/3.json"}]
fetch request:
fetch("/" + name + ".json")
.then(function(response) {
console.log(response);
return response.json()
}).then(function(json) {
var itemArray = populateItemArray(this, json);
populateListBox(name, itemArray);
}).catch(function(ex) {
console.log('parsing failed', ex)
});
console log result: (Response an object full of other objects but seems to be only an html response without any of my requested data)
Response {}
body: (...)
bodyUsed: false
headers: Headers
ok: true
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:3000/login?locale=en"
proto: Response
I am also receiving an error in the console using the fetch method which states the following: **
SyntaxError: Unexpected token <
**
Hope someone can assist. :)
UPDATE: After closely inspecting my headers in both requests I noticed the following: My AJAX request sends through a CSRF token, as well as a cookie in the header.
All fetch requests are made as anonymous and unauthenticated (by default)
All that was needed was to add an option to the fetch request as follows:
fetch("/" + name + ".json", **{ credentials: 'same-origin' }**)
.then(function(response) {
return response.json()
}).then(function(json) {
var itemArray = populateItemArray(json);
itemArray = sortByLabel(itemArray, 'label');
populateListBox(name, itemArray);
}).catch(function(ex) {
console.log('parsing failed', ex)
});
Problem is solved! Took me long enough - the CSRF token is not needed but the cookie is definitely required as that is what allows the request to be an authenticated one. :)
fetch requires a parameter to make its requests authenticated:
credentials: 'same-origin'
Not sure, maybe change dataType: "text" to "json"?