This question already has answers here:
How to call GraphQL API from Node.js/Express server?
(2 answers)
Closed 2 years ago.
I am trying to connect to a website and they have given me :
Url: https://api.demo...
headers:"x-api-key" and "x-api-user"
I do not know how to make the connection with them,I tried the code below:
const query = `
query {
some query here
}
`;
const url = ``
const opts = {
method: "POST",
headers: { "x-api-key": ,
"x-api-user": , },
body: JSON.stringify({ query })
};
Is this the right way? when I run it npm start=> App Crashes I am new to javascript and I dont even know how to make the search in google,can someone please guide me to a tutorial,link or please respond with the right way?
Thank you for your understanding
You can do it using the fetch call.
const query = `query {
Some query
}`;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query
})
})
.then(r => r.json())
.then(data => console.log('data returned:', data));
Related
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, {...})
This question already has answers here:
Trying to use fetch and pass in mode: no-cors
(9 answers)
Handle response - SyntaxError: Unexpected end of input when using mode: 'no-cors'
(5 answers)
Closed 4 years ago.
I have one API made in PHP, but i want consume with Reactjs using fetch, but i can not get, someone can help me?
handleSubmit = event => {
event.preventDefault();
const email = document.querySelector(".email").value;
const senha = document.querySelector(".password").value;
alert(JSON.stringify({email, senha}));
const res = {
method: 'POST',
mode:'no-cors',
body: JSON.stringify({email,senha}),
headers: new Headers({
'Content-type': 'application/json',
'Authorization': 'token here',
}),
};
fetch('http://rhvagas-api/login', res).then(res => {})
.then(result => {
console.log(res);
return result.json();
})
}
Error:
POSTMAN HERE:
Try
handleSubmit = event => {
event.preventDefault();
const email = document.querySelector(".email").value;
const senha = document.querySelector(".password").value;
alert(JSON.stringify({email, senha}));
const res = {
method: 'POST',
mode:'no-cors',
body: JSON.stringify({email,senha}),
headers: new Headers({
'Content-type': 'application/json',
'Authorization': 'token here',
}),
};
fetch('http://rhvagas-api/login', res).then(res => res.json())
.then(result => {
console.log(result);
// work with the result
})
}
This question already has answers here:
How do I POST a x-www-form-urlencoded request using Fetch?
(17 answers)
Closed 4 years ago.
I have written a JS function to post categoryId and shopId and page:0 to an api and this is my funciton :-
getInsideMenu(categoryid,shopid){
var formBody = [];
var details={
'categoryId':categoryid,
'shopId':shopid ,
'page':'0'
};
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
return fetch(
`${serverAddress}/api/shopProducts`,
{
method: 'POST',
body: formBody,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
).then((res)=>(res.json()))
},
But I'm getting null .I suppose the function is not defined properly. What can be done to fix it. It works well in POSTMAN.
[![this is in postman how I send][1]][1]
You're building an array of encoded name/value pairs and passing that directly as the body of the POST. But fetch doesn't accept an array in that parameter.
The minimal change to your code would be to join the array using & as the separator:
return fetch(
`${serverAddress}/api/shopProducts`,
{
method: 'POST',
body: formBody.join("&"), // <===== here
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
). /* etc */
Alternately, use FormData, as this is exactly what it's for: :-)
getInsideMenu(categoryid,shopid){
var formBody = new FormData();
formBody.set("categoryId", categoryid);
formBody.set("shopId", shopid);
formBody.set("page", "0");
return fetch(
`${serverAddress}/api/shopProducts`,
{
method: 'POST',
body: formBody,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
).then((res)=>(res.json()));
}
(Depending on your needs, you might use set or append. The above uses set.)
Side note 1:
This line:
).then((res)=>(res.json()));
...doesn't need most of those ():
).then(res => res.json());
Side note 2:
Don't forget to check for success; failing to do so is a common pitfall when using fetch. fetch doesn't reject on HTTP error (like 404 or 500). If you want to reject on HTTP error, you have to do it yourself:
return fetch(/*...*/)
.then(res => {
if (!res.ok) {
throw new Error(res.status);
}
return res;
})
.then(res => res.json());
Read this answer
You have to insert at least formBody = formBody.join("&"); after the loop.
This question already has an answer here:
Why express server receives front end data as undefined?
(1 answer)
Closed 12 days ago.
The community reviewed whether to reopen this question 12 days ago and left it closed:
Original close reason(s) were not resolved
I'm trying to build a react/node application and I was trying to pass a value which I get from user input to the nodejs api to call a separate api (Instagram API)
I want to attach an object to req.body from React app. I want to do something like this:
app.get('/hashtags', (req,res) => {
console.log(req.body);
console.log(req.body.tag);
});
This is my responsible react app code for the above node request:
handleChange(e){
const searchtag = 'hello';
fetch('/hashtags', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
tag: searchtag,
}),
})
}
I'm calling handleChange function when I click a button.
As for the above code I need my node api to call /hashtags with req.body.tag = 'hello' (as I'm passing 'hello' from reactjs).
But this gives me the following error:
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
If this can't be done this way: How can I attach an object to node api req.body from my react application?
If you want to pass string search tag why you are passing it in body. As per REST pass it in the url like this
handleChange(e){
const searchtag = 'hello';
fetch('/hashtags/' + searchtag, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
),
})
}
axios({
method: 'GET',
url: `${api.course}`,
headers: { Authorization: `Bearer ${localStorage.getItem('accessToken')}` },
data:{'category': "Design"}
})
I am working on integrating Cloudinary with my React Native app and am running into a problem when I go to upload using the Cloudinary API. I'm using React Native Image Picker to select an image from the camera roll and using that I get a source uri - example below.
I am getting an error response back from Cloudinary and I'm not sure what it's referring to. "Invalid file parameter. Make sure your file parameter does not include '[]'"
When I use the debugger, I can console log out all the params I am sending in the body of my request. Any suggestions would be much appreciated!
source.uri: /Users/IRL/Library/Developer/CoreSimulator/Devices/817C678B-7028-4C1C-95FF-E6445FDB2474/data/Containers/Data/Application/BF57AD7E-CA2A-460F-8BBD-2DA6846F5136/Documents/A2F21A21-D08C-4D60-B005-67E65A966E62.jpg
async postToCloudinary(source) {
let timestamp = (Date.now() / 1000 | 0).toString();
let api_key = ENV.cloudinary.api;
let api_secret = ENV.cloudinary.api_secret
let cloud = ENV.cloudinary.cloud_name;
let hash_string = 'timestamp=' + timestamp + api_secret
let signature = CryptoJS.SHA1(hash_string).toString();
let upload_url = 'https://api.cloudinary.com/v1_1/' + cloud + '/image/upload'
try {
let response = await fetch(upload_url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
file: {
uri: source.uri,
type: 'image/jpeg'
},
api_key: api_key,
timestamp: timestamp,
signature: signature
})
});
let res = await response.json();
console.log(res);
} catch(error) {
console.log("Error: ", error);
}
}
UPDATE
So I now have base64 encoding working, I think, but I am still getting the same error.
var wordArray = CryptoJS.enc.Utf8.parse(source.uri);
var file = CryptoJS.enc.Base64.stringify(wordArray);
try {
let response = await fetch(upload_url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
file: {
uri: file,
type: 'image/jpeg;base64'
},
api_key: api_key,
timestamp: timestamp,
signature: signature
})
});
So it turns out the source data I was passing in was not formatted correctly. I was able to pass it in from the ImagePicker plugin I was using as an already formatted data URI (the ImagePicker example comes with two ways to capture your source file and I was using the wrong one). I was able to get rid of the CryptoJS stuff and simply pass in file: source.uri
If you are using axios, make sure to include {'X-Requested-With': 'XMLHttpRequest'} in your request headers. eg.
const uploadAgent = axios.create({
baseURL: 'https://api.cloudinary.com',
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
});