when the SMS is sent using the API in template literal way works smoothly:
axios.post(
`https://api.fooserver.com/${API_KEY}/verify/lookup?receptor=${phone}&token=${code}`
)
.then(resp => resp.data)
whats wrong with the object param?
axios.post(`https://api.kavenegar.com/v1/${API_KEY}/verify/lookup`, {
receptor: phone,
token: code
})
.then(resp => resp.data);
it does send request but the object params.
Lucky I understood your question:), using params Axios will automaticity translate your object in query params.
Use this:
axios.post(`https://api.kavenegar.com/v1/${API_KEY}/verify/lookup`,{}, {
params: {
receptor: phone,
token: code
}})
.then(resp => resp.data);
In the first example, you are sending the data as query parameters, which isn't the same as sending it in the post body, as in the second example.
You can in fact pass your query parameters as an object, you just need to call .post a little differently:
axios
.post(
`https://api.fooserver.com/${API_KEY}/verify/lookup`,
{},
{
params: {
receptor: phone,
token: code
}
}
)
.then(resp => resp.data);
Or, if you so desire:
axios({
method: 'POST',
url: `https://api.fooserver.com/${API_KEY}/verify/lookup`,
params: {
receptor: phone,
token: code
}
})
.then(resp => resp.data);
You'll need to use querystring.stringify
Like this :
const querystring = require('querystring');
axios.post(`https://api.kavenegar.com/v1/${API_KEY}/verify/lookup`, querystring.stringify({
receptor: phone,
token: code
})
.then(resp => resp.data);
Related
I am writing a few API calls which are intertwined and pass on values to each other, there's a get token and store call then an get list of users and store user_id in order for both of those to be forwarded to the third DELETE user api call. The issue im encountering is with the url forming in the delete request. There's a special character in the user_id which is '|' this one. Notably when i pass the JS function decodeURIComponent on it, i get a proper result and the | character. But when calling the decoded variable inside the Cypress request method url option. It keeps ignoring the decode and encoding the character no matter where i try to put decodeURIComponent.
Heres a few examples of the method i tried using
Cypress.Commands.add('deleteCreatedUser', (token, user_id) => {
var userid = decodeURIComponent(user_id)
cy.log(userid)
cy.request({
method: 'DELETE',
url: "https://companydomain.auth0.com/api/v2/users/" + `${userid}`,
auth: {
bearer: `${token}`
}
})
.then((resp) => {
expect(resp.status).to.eq(204)
})
})
Or
Cypress.Commands.add('deleteCreatedUser', (token, user_id) => {
// var new_url = "https://companydomain.auth0.com/api/v2/users/" + `${decodeURIComponent(user_id)}`
// cy.log(new_url)
cy.request({
method: 'DELETE',
url: "https://companydomain.com/api/v2/users/" + `${decodeURIComponent(user_id)}`,
auth: {
bearer: `${token}`
}
})
.then((resp) => {
expect(resp.status).to.eq(204)
})
})
Or
Cypress.Commands.add('deleteCreatedUser', (token, user_id) => {
var new_url = "https://companydomain.auth0.com/api/v2/users/" + `${decodeURIComponent(user_id)}`
cy.log(new_url)
cy.request({
method: 'DELETE',
url: new_url,
auth: {
bearer: `${token}`
}
})
.then((resp) => {
expect(resp.status).to.eq(204)
})
})
All produce the same error message, the cy.log output is correctly:
https://companydomain.auth0.com/api/v2/users/auth0|63c92d19bc49af9a23ede481
but in the cypress request method that fails the URL is:
https://companydomain.auth0.com/api/v2/users/auth0%7C63c92d19bc49af9a23ede481
I am on Cypress version 12.3.0
So the decoding won't work in the Cypress request method, does anyone have a solution for this?
I am trying to send the param name in the Cloud Function managed by Firebase using POST method, I've read quite a few documentation, and no matter what I try it always returns undefined. Also is it safe to use this for sensitive data?
Client-Side
fetch(`https://<<APP-NAME>>.cloudfunctions.net/addCardForExistingCustomer`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
JSON.stringify(body: {'name': 'Name'})
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(err => console.error(err));
Server-side (Firebase Cloud-Functions)
exports.addCardForExistingCustomer = functions.https.onRequest(async (request, response) => {
let name = await request.body.name
response.json({
response: `${name}`
})
})
This question already has answers here:
How can I pass POST parameters in fetch request? - React Native
(2 answers)
Closed 1 year ago.
I need to add some parameters to this request:
fetch(url_ticket, {
//body: JSON.stringify(data),
//mode: 'no-cors',
param: {
'token': `${token}`,
'id': `${id}`,
'id_secret': `${id_secret}`
},
method: 'POST'
})
.then(response => {
console.log(response.text());
})
.catch(error => {
console.error(error);
});
However, I'm getting an error. I've made that request in Postman an it works, so the problem is obviously in this code. I think the error is in the params parameter; how can I add properly parameters in this request?
I'm literally new to js, i've searched for answers but i can't understand a thing, so posting my real problem has been my last option
Here is the code to send post request with parameter
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
For info you can read doc here Using fetch
I think this SO answer is a nice and clean way to do it. Basically, it constructs the URL string with parameters.
fetch(url_ticket + new URLSearchParams({
token: `${token}`,
id: `${id}`,
id_secret: `${id_secret}`
}), {});
You could also construct the parameters in a more manual way, by inserting the variables into a backticked URL string:
let url = `${url_ticket}?token=${token}&id=${id}&id_secret=${id_secret}`;
fetch(url, {...})
I am trying to write a basic graphql query with fetch that works when using apollo client. But it does not work with node-fetch.
The type definitions look like this:
type Query {
findLeadStat(print: PrintInput!): LeadStatWithPrint
}
input PrintInput {
printa: String!
service: String
}
type LeadStatWithPrint {
answered: Int!
printa: String!
service: String
}
This is the node-fetch query:
const fetch = require('node-fetch');
( async () => {
const uri = `http://localhost:3000/graphql/v1`;
const query = `
query findLeadStat(print: PrintInput!) {
findLeadStat(print: $print){
answered
printa
service
}
}
`;
// I also tried add a query: key inside data object
const data = {
print: {
printa: "62f69234a7901e3659bf67ea2f1a758d",
service: "abc"
}
}
const response = await fetch(uri, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({query, data})
});
console.log('and the resp: ', response);
})()
It gives me:
url: 'http://localhost:3000/graphql/v1',
status: 400,
statusText: 'Bad Request',
It works in Apollo GraphQL Client. Why doesn't it work with fetch?
So when I was using async await with node-fetch, the response was pretty much useless. It was just telling me there was a 400 bad request error and then give me this long object of properties, none of them containing the actual error message.
But when I changed the fetch call to this:
const response = await fetch(uri, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query, variables}) // same as query: query, variables: variables
})
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.error('ERROR: ', err));
There two lines right here:
.then(res => res.json())
.then(json => console.log(json))
made it clear what the issue was:
{
errors: [
{
message: 'Syntax Error: Expected $, found Name "fingeprint"',
locations: [Array],
extensions: [Object]
}
]
}
It appears node-fetch has two async events occurring and so await had to be used twice:
const response = await fetch(uri, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query, variables}) // same as query: query, variables: variables
})
console.log('and the resp: ', await response.json());
A 400 status indicates your query was invalid or malformed. When this happens, the response will include a JSON body with an errors array that can be inspected to determine what exactly went wrong.
In this particular case, the issue is that your query includes a non-nullable variable ($print) but this variable was not provided along with the query.
When making a GraphQL request, the request body should be a JSON object with a query property and two other optional properties -- variables and operationName. operationName is used to identify which operation to execute if multiple operations were included in the provided document (the query property). Any non-nullable variables defined in the executed operation must be included as properties under the variables property, which is also an object. Nullable properties may be omitted altogether.
In other words, you need to change the data property in your request to variables in order for the server to recognize that the variable was provided with the request.
I am trying to post on an API with some query params.
This is working on PostMan / Insomnia when I am trying to by passing mail and firstname as query parameters :
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
However, when I am trying to do it with my react native app, I got a 400 error (Invalid Query Parameters).
This is the post method :
.post(`/mails/users/sendVerificationMail`, {
mail,
firstname
})
.then(response => response.status)
.catch(err => console.warn(err));
(my mail and firstname are console.logged as follow: lol#lol.com and myFirstName).
So I don't know how to pass Query Parameters with Axios in my request (because right now, it's passing data: { mail: "lol#lol.com", firstname: "myFirstName" }.
axios signature for post is axios.post(url[, data[, config]]). So you want to send params object within the third argument:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
As of 2021 insted of null i had to add {} in order to make it work!
axios.post(
url,
{},
{
params: {
key,
checksum
}
}
)
.then(response => {
return success(response);
})
.catch(error => {
return fail(error);
});
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
You can use params and body together in a request with axios
sendAllData (data) {
return axios
.post(API_URL + "receiveData", JSON.stringify(data), {
headers: { "Content-Type": "application/json; charset=UTF-8" },
params: { mail: xyx#example.col }, //Add mail as a param
})
.then((response) => console.log("repsonse", response.status));
}