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.
Related
I have an asynchronous JavaScript function which fetches data from the server. However, I've noticed that if a user goes into their console in the browser, they can repeatedly call this function from the console and make endless requests to the server to fetch data.
This question is about website security and request authorizations. I want to limit the client to making one request to the server for data per page visit so that the data fetching resources on the back end can't be DDOS'd.
Do I need to build a system on the backend to make it so that only one request to the server to fetch data per page visit is allowed, and the user can't spam this function on the client side? Or can the number of requests being made to the server be limited to one on the client side using JS?
Here is my JS code as an example
var numberOfRequests = 0;
async function getResults() {
if(numberOfRequests !== 0){
return;
}
numberOfRequests = numberOfRequests + 1;
console.log("Fetching data");
var postData = {
test: "test"
};
const response = await fetch("https://example.com/test.php", {
method: "POST",
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate'
},
//make sure to serialize your JSON body
body: JSON.stringify({
postData
})
});
const data = await response.text();
if(data){
console.log(data)
}
}
getResults();
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'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.
I am working on React web application with a Node backend in which I have implemented the functionality to upload an Excel sheet. If the Excel sheet contains fewer records then it is uploaded successfully. But if there are more than 4,000 records then HTTP request terminates but process in backend goes on. I don't want to abort the request until the response comes from the backend.
I have tried AbortController, axios. But not working for me.
front end api call
code:
const data = new FormData();
data.set("supplier_id", parseInt(this.state.productInfoFormData.productInfoSupplierId));
data.set("supplier_name", this.state.productInfoFormData.productInfoSupplierName);
data.append(
"upload_xlsx",
this.state.isNew == true
? this.state.productInfoFormData.productInfoAttachment
: ""
);
axios({
method:'POST',
url: 'http://localhost:9001/addProductInfo',
timeout:1000*300,
data,
headers: {
'Content-Type': 'application/json',
}
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
I'm creating a registration system for a university project. This is using fetch to post the data from the form to a PHP file.
I want to transfer over a $message variable that is echoed at the bottom of my PHP page to know if the registration has been successful, or if an error message has occurred. If I can see that the $message equals my success string, I think I can do an if statement using window.location.href like below? Currently it is redirecting the page for any successful fetch, no matter what the response from PHP is.
I've tried using header("Location: /index.html"); in my PHP file on the success line, but this also didn't work for me. I've spent hours looks for a solution but I really can't get my head around how to pass this variable over.
var myJSON = JSON.stringify(userDetails);
fetch("url/register.php", {
method: "POST",
mode: "no-cors",
cache: "no-cache", /
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
},
redirect: "follow",
referrer: "no-referrer",
body: myJSON
}).then((response) => {
if (response.ok) {
return response.blob();
} else {
throw new Error("Things went poorly.");
}
}).then((response) => {
//Fetch was successful!
window.location.href = "url/index.html";
}).catch((error) => {
console.log(error);
});
You can try this in your php file:
$response = [ message => "the message", success => true ];
echo json_encode($response);
You will receive a JSON response which you will use it to validate if the request was successful.
In your javascript code, you have to parse this JSON response to an literal object like:
fetch(url, {params})
.then(response => response.json())
.then((response) => {
if (response.success) {
// fetch was succesfull!
} else {
// response.message could be used to show what was wrong
throw new Error(response.message);
}
})
One way to accomplish this is to use the URL's query parameters to pass the success message. For example:
window.location.href = "url/index.html?login=success";
Then on the .html page you would have code that looks for the login query parameter and displays something if it's equal to success.