Add parameters to post request using js on client side - javascript

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

Related

js with express and prisma- delete function is still triggering insert (prisma create function on server side)

I am using express with js to delete a record from my azure sql database (prisma is the orm). The post method worked on the leads route. The delete did not work...it is posting empty record to Leads table rather than triggering the delete function on the server side:
--Client Side Script
document.querySelector('#delete_leads_form').addEventListener('submit', function(e){
e.preventDefault();
const inputs = document.querySelectorAll('#delete_leads_form input, #delete_leads_form select')
const payload = {};
inputs.forEach(input=>{
payload[input.name] = input.value
})
async function deleteReq(){
try {
const response = await fetch('https://hh-events-internal.herokuapp.com/lead', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(payload)
} )
const responseJson = await response.json()
console.log('response', responseJson)
} catch (error) {
console.error(error)
}
}
deleteReq()
})
I have tried changing the client side method to DELETE, and no luck.

How can I update the message body using gmail API in javascript

I have got the message body. Now I want to update it according to my needs. I am using this login/code. but it says 400 error. I think issue is in body parameter of the request. Would you please help me there?
var token = localStorage.getItem("accessToken");
var messageId = "18514426e2b99017";
async function updateMessageBody() {
var updatedBody = "Hello,\n\nThis is the UPDATED message body.\n\nBest regards,\nJohn";
const API_KEY = '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-CXIk';
const headers = {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
};
const response = await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages/18514426e2b99017/modify?key=['API_KEY']`, {
method: 'POST',
headers: headers,
body: JSON.stringify({
raw: window.btoa(unescape(encodeURIComponent(updatedBody)))
})
});
if (!response.ok) {
// throw new Error(`Request failed with status code ${response.status}`);
}
return await response.json();
}
updateMessageBody()
.then(response => {
console.log('Message body updated successfully:', response);
})
.catch(error => {
});
Checking the documentation, it states that a message body can't be altered once it has been created, meaning that once you have already created an email this message can't be changed. You can verify this here.
You can instead update a message draft which is possibly what you are trying to do, however using the endpoint you have in your code this won't be possible and will lead to the error message you are getting, try using instead the users.draft.update method that allows you to modify the content of the draft sitting in your mailbox. Please note as well that using the method users.messages does not have any update method as they only have the modify one's, those methods can only update the labels though so please be aware of that.

Why can't I send a form data from axios?

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);
});

Axios: Send variable in the body of a POST request and not params

I am working on a project where i need to send authentication variables in the body of the request and not as parameters. I see that a POST request sends the second parameter as the body in the documentation but I am getting an error in the .NET service.
_response: "{"error":"invalid_clientId","error_description":"ClientId should be sent."}"
I was getting the same error in PHP when I wasn't send the params in the body but the values are all the same that I am using in this POST request so I know the params and values are correct.
Here is what I have:
axios.post(`https://myawesomeapi.com`,
{username:this.state.email_address, password:this.state.password, grant_type:'password', client_id:'thisAppsClientID'},
{headers: { 'content-type':'application/x-www-form-urlencoded', 'accept':'application/json' }}
).then( res => {
let result = res.data;
console.log(result);
})
.catch( (e) => { console.log(e.response); });
When I console.log and inspect the error response I see this:
config:
adapter: ƒ xhrAdapter(config)
data: "{"username":"myusername","password":"mypassword!","grant_type":"password","client_id":"thisAppsClientID"}"
headers: {Accept: "application/json, text/plain, */*", Content-Type: "application/x-www-form-urlencoded"}
...
Here is what I have in guzzle that is working if that helps:
$this->client->request('post', 'https://myawesomeapi.com',
['form_params' => ['username' => $input['username'], 'password' => $input['password'], 'client_id'=>'thisAppsClientID', 'grant_type'=>'password']],
['headers' => ['accept' => 'application/json','Content-Type' => 'application/x-www-form-urlencoded']]);
Is the username, password, grant_type, and client_id being passed as the body? Did I mess up how to send the headers? Thanks and let me know!
I know I had similar problems with axios that I never quite figured out. However, I was able to get post requests to work with Form Data. Try the snippet below. I hope it works.
const dataForm = new FormData();
dataForm.append('username', this.state.email_address);
dataForm.append('password', this.state.password);
dataForm.append('grant_type', 'password');
dataForm.append('client_id', 'thisAppsClientID');
axios.post('https://myawesomeapi.com', dataForm)
.then(res => {
let result = res.data;
console.log(result);
})
.catch(e => {
console.log(e.response);
});

can't get success response data/status from node/express to my client app(react): "referenceerror response is not defined"

i've made a basic node/express server, and have a route that handles submission of form data(i've made using react), the post request is handled using async/await with fetch api.. i'm not sure if the issue is with my server-side route or my implementation of the post request with async/await fetch. however the server does receive the form data it just doesn't return a response.
my code:
node/express route
router.post('/add', function (req, res) {
console.log(req.body);
res.json({success : "Updated Successfully", status : 200});
});
note: the console.log(prints the expected data, but the response isn't being picked up by client correcly)
post request implementation:
const postRequestHelper = async (routePath, objectPayload) => {
console.log("posting payload object: ");
console.log(objectPayload);
const rawResponse = await fetch(routePath, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(objectPayload)
});
const response = await rawResponse.json();
return response;
};
export default postRequestHelper;
form submission code where post request is called:
async handleSubmit(event) {
if(typeof this.state.validationMessages === "undefined"){
// create payload data object
let objectPayload = Object.assign({}, this.state);
for(let key in objectPayload){
if(!isInObject(key, formKeyConstants)) // delete any prop keys that aren't in formPropertyKeys js file
delete objectPayload[key]
}
// send post request
console.log(objectPayload);
const response = await postRequestHelper("http://localhost:8080/user/add", objectPayload);
// log response data
console.log("response");
console.log(response);
}
event.preventDefault();
}
What about trying in your server
return res.send(JSON.stringify({success : "Updated Successfully", status : 200}));
issue was with async await fetch api it seems, issue with await was breaking the response from the server.
If routing takes place in app , then use :
app.use(express.json)
If routing takes place in router folder , then use :
router.use(express.json)
It'll by default uncover the req.body into json format.(For which installing and initializing express is a must)

Categories

Resources