i am trying to insert data into a local server but the data is not being inserted. I am using the JSON server package, and i am trying to insert to the endpoint: './users'.
Here is the code:
form.addEventListener('submit', (event) => {
window.sessionStorage.setItem("Slot", JSON.stringify(slot.value))
fetch('http://localhost:3000/users', {
method: 'POST',
body: {
"name": window.sessionStorage.getItem("name"),
"age": window.sessionStorage.getItem("age"),
"carBrand": window.sessionStorage.getItem("carBrand"),
"details": window.sessionStorage.getItem("details"),
}
}).then((response) => {
console.log(response)
}).then((data) => {
console.log(data)
})
This seems to be working fine, cause once i submit the form, an instance of an object is created, but the data is not being pulled to the API and i also logged the response coming from the server, and it all seems to be working fine.
Related
I am consuming an api that asks me to send a filter series within a formData, when doing the tests from Postman everything works without problem, I tried with other libraries and it also works without problem, but when trying to do it from axios the information does not return with the filters.
This is the code I am using:
const axios = require('axios');
const FormData = require('form-data');
let data = new FormData();
data.append('filtro_grafica', '2,0,0,0');
let config = {
method: 'get',
url: 'https://thisismyurl/filter',
headers: {
'Authorization': 'JWT MYTOKEN',
...data.getHeaders()
},
data : data
};
axios(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
You can send Form-data using get method, but the most servers, will reject the form data.
However it is not recommended anymore. The reason is, first because it is visible in the URL and browsers can cache them in it’s history backstacks, and second reason is because browsers have some limitations over the maximum number of characters in url.
If you are to send only few fields/input in the forms you can use it but if you have multiple inputs you should avoid it and use POST instead.
At the end it depends on your own usecase. Technically both GET and POST are fine to send data to server.
replace get with post
const axios = require('axios');
const FormData = require('form-data');
let data = new FormData();
data.append('filtro_grafica', '2,0,0,0');
let config = {
method: 'post',
url: 'https://thisismyurl/filter',
headers: {
'Authorization': 'JWT MYTOKEN',
...data.getHeaders()
},
data : data
};
axios(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
I have a react frontend and node backend, I am fetching a list of objects from an external API using Axios and then trying to pass it to my node backend. The issue is that the node backend is not able to receive this payload data on the backend, req.body returns an empty object.
To debug, I've seen what happens in the network tab, and have observed that the payload data just returns the data type instead of the actual data as shown below.
enter image description here
Here is what my front-end code looks like:
let faqlist = "";
// fetching data from one api
await axiosinstance
.get(
"https://linktotheapi/api/faq"
)
.then((res) => {
faqlist = res.data;
console.log("This is faqlist", faqlist);
console.log(typeof faqlist);
// passing the data fetched from 1st api to node/express backend.
fetch("/create-page", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: faqlist,
});
});}
You can stringify the array of objects before sending. Use JSON.stringify
const x = [{ x: 1 }, { x: 2 }];
fetch("https://httpbin.org/post", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(x)
});
I am fetching JSON data with CORS and I am getting the JSON data in my console successfully. Now I want to display the fetched data with PHP. What are the next steps after the code below to get the fetched data into PHP?
<script>
fetch("http://localhost:8000/get_users.php", {
method: 'post',
credentials: 'include'
}).then(response => {
return response.json();
}).then(users => {
console.log(users);
});
</script>
I tried to get it in $_POST:
$posted_data = array();
if (!empty($_POST['users'])) {
$posted_data = json_decode($_POST['users'], true);
}
print_r($posted_data);
But users is undefined.
Does someone know how to get the fetched JSON users into PHP?
Thanks!
Okay I found a solution that might bring me one good step further. I need to JSON.stringify() my fetched JSON, that was the issue.
UPDATED CODE:
<script>
fetch("http://localhost:8000/get_users.php", {
method: 'post',
credentials: 'include'
}).then(response => {
return response.json();
}).then(users => {
console.log(users);
var users = JSON.stringify(users);
alert(users);
});
</script>
After deploy react.js application on server I am getting error in contact form as in title. On localhost the form worked without any errors. The problem occurs just after clicking the sumbit button on the form. Then you can see the error in the console. Do any of you see any error in the code below? Where can I look for a solution to this error?
Live version of the contact page
Contact page
ContactForm.js
const ContactForm = () => {
const [status, setStatus] = useState("Submit");
const handleSubmit = async (e) => {
e.preventDefault();
setStatus("Sending...");
const { name, email, subject, business, datetime, launch, message } = e.target.elements;
let details = {
name: name.value,
email: email.value,
subject: subject.value,
business: business.value,
datetime: datetime.value,
launch: launch.value,
message: message.value,
};
let response = await fetch("https://delightart.co/send", {
method: "POST",
headers: {
"Content-Type": "application/json;charset=utf-8",
},
body: JSON.stringify(details),
});
setStatus("Submit");
let result = await response.json();
alert(result.status);
};
That's because the response body of fetch is not in JSON format, so when you
use response.json(), it threw the error. So you need make sure whether response is a JSON, either you can use it without calling response.json() or use JSON.stringify() in the backend service to turn the data into JSON format before sending it.
You can check Response apis in MDN https://developer.mozilla.org/en-US/docs/Web/API/Response.
And response.json() inherits from body.json(), so you can check it for more details. https://developer.mozilla.org/en-US/docs/Web/API/Body/json
I'm developing a "TODO" app using node.js and mongodb.
I'm trying to post a new task from the client but I didn't success to pass parameters to the server and from there to the database.
Client code:
<script>
function addData(item, url) {
var text = document.getElementById("myTask").value;
return fetch('/todos',{
method: 'post',
body: text
}).then(response => response.json())
.then(data => console.log(data));
}
</script>
Server code:
app.post('/todos',(req,res) =>{
console.log("\n\n req.body is: \n\n",req.body);
var todo = new Todo({
text: req.body.text});
todo.save().then((doc) =>{
res.send(doc);
console.log(JSON.stringify(doc,undefined,2));
},(err) =>{
res.status(400).send(err); //400 = unable to connect
console.log("Unable to save todo.\n\n\n" , err);
});
});
And the problem is that the client doesn't send the body to the server,
and the body is null on the server side:
See the logs here
(as you can see: req.body = {})
In the js code, I tried to pass the body parameter but I guess I did something wrong so I want to know the best way to pass parameters back to the server (not only the body but text, time and etc)
Thank in advance,
Sagiv
I think that you are missing something. Try to use name of param
body: JSON.stringify({data: text})
OR
read here Fetch: POST json data
I used this code:
(async () => {
const rawResponse = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 1, b: 'Textual content'})
});
const content = await rawResponse.json();
console.log(content);
})();
and now I succeeded to pass data to the request.
Thanks everybody