I am using Nodejs, Express, MySQL, body-parser and EJS.
What I am trying to do is, when someone press on a button, it sends a PUT request which will update the counter by 1, I am trying to send the ID of the pressed button so it can be incremented by 1.
app.put("/toolong", function(req,res){
console.log(res.status(200).json({voteNum: 5}))
}
)
The Fetch:
function upvote(click){
// when the upvote button is clicked
let idOfClicked;
console.log(event.target.attributes[1].value)
idOfClicked = event.target.attributes[1].value
fetch(`/toolong`, { method: 'PUT', data: {id:9} })
.then(res => res.json())
.then(jsonRes => {
console.log(jsonRes.voteNum) // gives 5
})
}
I am trying to send the variable idOfClicked from the Fetch to my app.put so I can do a SQL query which will use that variable.
I assume you are able to do it, the "data" key in the fetch is something I tried from seeing some examples but I wasn't able to send it through
It's a body key instead of data.
I fixed it, the problem was I didn't have "headers: new Headers({ "Content-Type": "application/json" })" in my app.put, I placed it after my "body"
Related
I am a university student and this is my first time of putting all together of server, api and client sides.
My problem is that first I have created an API using Django-Rest framework.
When I post data to that server using fetch function in JavaScript, it keeps posting that data and does not stop until I close. In the server database, many same data have been created.
I cannot figure out how to fix it. My intention was I want to post the data just once.
Please help me how to do it.
Thank you.
This is my javascript code π
const testPost = () => {
fetch('http://127.0.0.1:8000/mysite/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'player1Hp': 30,
'player2Hp': 20
})
})
.then(res => {
return res.json()
})
.then(data => console.log(data))
.catch(error => console.log('ERROR'))
}
This is views.py in Django π
views.py photo
This is many POST messages in terminal cause of infinite looping πterminal photo
This is full screenshoot of script.js π script.js photo
HTML just calls script and the rest is just blank. π index.html photo
The useEffect() is responsible for displaying all data (it gets an array). When the user navigates to the page, all photos will be displayed automatically.
Once the user uploads successfully and you refresh the page, the uploaded photo correctly appears on the bottom along with the other already uploaded photos above it.
However, I'd like the newly uploaded photo to appear at the top instead of the bottom upon the user uploading data.
In other words, move it to element to the front of the array so that when the user refreshes, the data appears on top and not on the bottom.
I know unshift() should be used to achieve this but I've tried many ways in the fileUpload() function but to no avail. How can I achieve this? Should this even be handled on the client side or server?
useEffect(() => {
const headers = {
"Accept": 'application/json',
"Authorization": `Bearer ${authToken}`
};
axios.get('http://127.0.0.1:8000/api/get-user-uploads-data', {headers})
.then(resp => {
setGridData(resp.data);
}).catch(err => {
console.log(err);
});
}, []);
const fileUpload = () => {
const url = 'http://127.0.0.1:8000/api/file-upload';
let formData = new FormData();
let imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
const headers = {
"Accept": 'application/json',
"Authorization": `Bearer ${authToken}`
}
axios.post(url, formData, {headers})
.then(resp => {
let first = localStorage.getItem('UserID') === gridData[0]['UserID'];
gridData.unshift(first);
}).catch(error => {
console.log(error);
});
};
If you're refreshing the page, your component is reloading and your API call inside useEffect is getting the fresh copy of the data from the server side again.
If you really want your data to be displayed in the latest upload first order, you could sort them with timestamps(if you have that information available) or get this data sorted already from the server side.
Keep in mind that if you have a long list and plan to paginate it, it's better to do it on the server side otherwise on each fetch the sorting on the frontend side will not look very good because of some other items shifting randomly.
Let, I have developed two websites: A and B.
I have created a link on the react A website.
And I want to get the link from the react B website.
How can I do that?
You can get the link from the react B website by parameter from URL
Are your trying get data from "website" (parse HTML) or data from server using REST API?
In option 2, your server should return header with:
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: *
to execute request from another domain.
Then you can use fetch method to get data from server like this:
fetch( ConfigX.restApi + "/r,get_training" , {
method: 'POST',
body: JSON.stringify(dataPost),
})
.then( res => res.json() )
.then(json => {
//console.log(JSON.stringify(json) );
this.setState({
rows: json.rows,
result: json.result
});
});
const access_token = ""
fetch('https://api.fitbit.com/1/user/-/profile.json', {
method: "GET",
headers: {"Authorization": "Bearer " + access_token}
})
.then(response => response.json())
//.then(json => console.log(json))
.then((out) =>
{
console.log(out.data);
document.getElementById('log').innerHTML=out.data;
})
hi, I have been trying to fetch wep API using the above js code. i have successfully fetched the data inside my debug console but now I want to fetch inside my firebase. Can someone help with this. For security purpose i removed the access token.
You code seems OK. Either your access token is not correct, or the JSON object you receive has no "data" key.
If I'm on the right page, it seems that you should use "out.user" instead of "out.data":
https://dev.fitbit.com/build/reference/web-api/user/get-profile/
make sure the out.data is string not an array or object.
I want to post with the Fetch API and call an action from my controller but the action is not being loaded like when I would do it with submitting a post form.
function postQuery() {
let query = document.getElementById("query").value;
fetch('/actionName', {
method: 'POST',
body: query,
headers:
{
"Content-Type": "application/x-www-form-urlencoded"
}
})
.then(response => {
console.log(response);
})
.then(data => {
console.log('Success:', data);
})
}
/actionName is not being loaded, I am supposed to be directed to a different page.
When I would submit a form like that:
<form action="/actionName" method="post">
the public function actionName would be called but with fetch its not working.
When i try to see the $_POST with var_dump($_POST) inside of actionName, I am getting an empty array...I dont understand this
I see two questions here:
Why is the data not accessible to the server
Why is the brower not redirected to /actionName
Answer to #1:
Make sure the content type header matches the data you are sending, if it is raw json, you should use application/json rather then application/x-www-form-urlencoded. If you want to send a form using fetch API, you would need to either serialize to form to a URL encoded format, or use FormData, for example:
var fd = new FormData(document.getElementById('myForm'))
fetch('/actionName', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data;'
},
body: fd
})
Answer to #2:
Submitting HTML Forms will direct the browser to the forms action, so if I submit a form to /actionName, I will end up seeing the HTML that is returned by the server for that route. Using Fetch API to submit a form is a type of AJAX, which means that it is capable of communicating with the server without needing to load a new page.
With that in mind, you have a few options:
Use a regular form so that the desired default behavior happens
Manually redirect the user somewhere after the fetch promise resolves, something like:
fetch(/*..*/).then(data => {
console.log('Success:', data);
window.location.href = '/otherPage'
})
Render the response HTML without redirecting the user, something like:
fetch(/*..*/).then(data => {
console.log('Success:', data);
data.text().then(rawHTML => {
document.body.parentElement.innerHTML = rawHTML
})
})
My personal intuition would be to go with the first option, as it suits your requirements and is the simplest.