How to pass a query param in post call in Reactjs - javascript

I am new to reactjs.I am doing a post call but not sure, how to pass a boolean value in url as a query param in reactjs. For eg: http://www.abx.com?example=true. How do I pass this example in post api call.
Endpoint: API_SAMPLE: "/sample",
post call:
postCall() {
const config = {
headers: {
accept: "application/json",
"Content-Type": "application/json",
},
};
const data = {
product: {
body
},
};
return http
.post(this.API.API_SAMPLE, data, config)
.then((response) => {
return response.data;
})
.catch((error) => {
throw error;
});
}
i want to add a boolean value in my query param, how will i do that

You can use template literals to pass the variable to your URL.
const example = true;
const url = `http://abx.com/sample?example=${example}`
or use it this way:
return http.post(`${this.API.API_SAMPLE}?example=${example}`, data, config) {...}

wether you are using POST or GET you will have to modify the URL.
You can do this "dynamically" or you can use something like URLSearchParams:
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
var URL = "http://example.com/search";
var searchParams = new URLSearchParams(URL);
searchParams.append("example", "true");
searchParams.toString() // "http://example.com/search?example=true";
Just make sure you support the correct browsers:
https://caniuse.com/#search=urlsearchparams

Related

How to building a fetch call to pass value to a method that expects an Object?

I currently not sure how to use a fetch post call to pass an object to a method expecting that object. I created a payload and passed it but does not seem to work. I have set a breakpoint in the code behind but it is never hit. Not sure why the fetch call is not working. Any suggestions on way the endpoint is not being reached?
This is my method in C#.
[HttpPost]
[Route("ResetPassword")]
private void ResetPassword(Player player){
{
Javascript:
const continueBtn = document.getElementById("continueBtn");
continueBtn.onclick = () => {
const email = document.getElementById("lblEmail").innerHTML;
sendResetEmail(email);
}
async function sendResetEmail(email) {
const payload = {
email: email
}
const data = new FormData();
data.append("json", JSON.stringify(payload));
let sendResetEmail = await fetch(`/ResetPassword`,
{
method: 'POST',
body: data
});
}
if you don't want to provide the name of the parameter in your client, you need to give the [FromBody] attribute in your API:
[HttpPost]
[Route("ResetPassword")]
private void ResetPassword([FromBody] Player player){
}
Then, on the client, there are multiple ways, but the most common/modern is to use JSON encoding:
const payload = {
email: email
}
const data = JSON.stringify(payload);
let sendResetEmail = await fetch(`/ResetPassword`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: data
});
}

How can I delete some data from Firebase Realtime Database?

I have this functions to save and get data on it:
to save:
try {
const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations.json', {
method: 'post',
body: JSON.stringify(addNewLocation)
})
const response = await fetch(request)
window.location.reload()
return await response.json()
} catch (error) {
alert('Try again: ', error)
}
//to get:
try {
const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations.json', { method: 'get'})
const response = await fetch(request)
return await response.json()
} catch (error) {
alert('Try again: ', error)
}
And when I use "delete" instead of "get" it deletes the locations folder entirely, but when I use a link with a key at the end of the link, I get an error
You need make a DELETE request at the location you need to delete.
curl -X DELETE \
'https://[PROJECT_ID].firebaseio.com/locations.json'
const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations.json', { method: 'DELETE'})
const response = await fetch(request)
return await response.json()
I'm not sure about how your database structure looks like but the above request will delete the whole "locations" node. Here's an example:
If you want to delete only location2, then make a delete request at https://[PROJECT_ID].firebaseio.com/locations/location2.json
I'm not sure if there's any specific reason for you to use the REST API but you can try using Firebase Web SDK. It's easier to use, for example to delete location2:
firebase.database().ref("locations/location2").remove()
you can use the remove method
let userRef = this.database.ref('users/' + userId);
userRef.remove()
You can use the following code
deleteSomeData(id) {
fetch(
// don't add .json at [data Name]
`https://[your FireBase project url]/[data Name (don't add .json)]/${id}.json`,
{
method: 'Delete',
headers: {
'Content-Type': 'application/json',
},
}
)
.then((response) => {
if (response.ok) {
// if sucess do something
} else {
// if fail throw error
throw new Error('could not delete data');
}
})
.catch((error) => {
this.error = error.message;
console.log(id);
});
},
You can user item id to delete it like below.
const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations/<localtion_id>.json', { method: 'delete'})
your location id can be value like this, -MyB0qQoQuf9lPnwderfg

Sending multiple cookies using Fetch in javascript

I am trying to send two cookies using Fetch in Javascript.
This is my function:
var cid_and_auth = process.argv[2];
const fetch = require("node-fetch");
function usePairService()
{
cid = cid_and_auth.split(" ")[1];
auth = cid_and_auth.split(" ")[0];
(async () => {
await fetch(AUTHENTICATIONURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': CONTENTTYPE,
'wpay-meta': userPairwpaymeta,
'cookie': 'cid'=cid,'auth'= auth,
},
body: JsonBody,
})
});;
}
I am trying to send cookies in the header, but it's giving an error, saying invalid left-hand die in expression. Any help will be appreciated.
'cid'=cid tries to assign the value of cid to the string value 'cid'. You cannot assign to a string, hence the error.
You have to build up a string of <key>=<value>; pairs. If you have each value in a variable you can either manually build the string, e.g. using template literals:
{
// ...
Cookie: `cid=${cid};auth=${auth}`,
}
or you could create an object from those variables and programmatically create the string (which makes it a bit easier to add more values later on):
const cookieData = {cid, auth};
// ...
{
// ...
Cookie: Object.entries(cookieData)
.map(([key, value]) => `${key}=${value}`)
.join(';'),
}

MERN Stack, axios post current state to DB error 400 bad request [duplicate]

I am trying to create a postHTTP request with some form parameters that are to be set. I am using the axios with node server. I already have a java code implementation of constructing a url as given below:
JAVA CODE:
HttpPost post = new HttpPost(UriBuilder.fromUri (getProperty("authServerUrl"))
.path(TOKEN_ACCESS_PATH).build(getProperty("realm")));
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new NameValuePair("username",getProperty ("username")));
formParams.add(new NameValuePair("password",getProperty ("password")));
formParams.add(new NameValuePair("client_id, "user-client"));
I am trying to do the same thing in axios.
AXIOS IMPLEMENTATION:
axios.post(authServerUrl +token_access_path,
{
username: 'abcd', //gave the values directly for testing
password: '1235!',
client_id: 'user-client'
}).then(function(response) {
console.log(response); //no output rendered
}
Is the approach to set these form params on the post request correct?
You have to do the following:
var querystring = require('querystring');
//...
axios.post(authServerUrl + token_access_path,
querystring.stringify({
username: 'abcd', //gave the values directly for testing
password: '1235!',
client_id: 'user-client'
}), {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function(response) {
console.log(response);
});
If your target runtime supports it, Axios is able to accept a URLSearchParams instance which will also set the appropriate Content-type header to application/x-www-form-urlencoded
axios.post(authServerUrl + token_access_path, new URLSearchParams({
username: 'abcd', //gave the values directly for testing
password: '1235!',
client_id: 'user-client'
}))
The same goes for the fetch API
fetch(url, {
method: "POST",
body: new URLSearchParams({
your: "object",
props: "go here"
})
})
Why pull in another library or module to do something so simple with pure vanilla JavaScript? It's really one line of JS to produce the desired data to submit in your POST request.
// es6 example
const params = {
format: 'json',
option: 'value'
};
const data = Object.keys(params)
.map((key) => `${key}=${encodeURIComponent(params[key])}`)
.join('&');
console.log(data);
// => format=json&option=value
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data,
url: 'https://whatever.com/api',
};
const response = await axios(options); // wrap in async function
console.log(response);
I agree with jhickok, no need to pull in an additional library however their code will not produce a correct result due to the usage of Object.entries, you would expect to see the following:
"format,json=0&option,value=1"
Instead Object.keys should be used.
const obj = {
format: 'json',
option: 'value'
};
const data = Object.keys(obj)
.map((key, index) => `${key}=${encodeURIComponent(obj[key])}`)
.join('&');
console.log(data); // format=json&option=value
Then of course...
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data,
url: 'https://whatever.com/api',
};
const response = await axios(options);
const body = new URLSearchParams();
body.append('param1', 'param1_value');
...
...
axios.post(url,body)

Passing parameters in get query to vue js?

I do the filtering, when I click on the apply filter, the query in the API flies away
php-developer, says that the request should be get, not post
how to pass parameters to the get query?
example for my post request
export const filterDate = (options) => {
console.log(options)
return axios.post(url, options).then(({ data }) => {
if (data.errors) throw new Error(JSON.stringify(data.errors));
return data;
})
};
but if I just replace the post on the get parameters are not transferred
If you want to pass parameters in get request, pass an object with "params" property, as follow:
axios.get('/user', {
params: {
ID: 12345
}
});
in options you specify a param object:
params: {
k: val
},
or by building an UrlSearchParam object:
const params = new URLSearchParams();
params.append('k', 'val');
axios.get(url, params);

Categories

Resources