How can I view the request that Javascript fetch sends to the server when I do something like this:
var h = new Headers({
"X-API-Key": KEY,
});
var obj;
fetch(url, {
headers: {h}
}).then(response => response.json())
.then(data => {
obj = data;
})
.then(() => {
console.log(obj);
});
similar to the output given by curl -v?
Thanks
Edit: I am using React Native.
To be more clear, what I am asking is that I know under the hood fetch is creating and using a Request object, is there a way to print the generated object. I am aware that I can create my own request object and pass that to fetch instead of a url but that is not what I want to do.
Related
The function below is contained in the Apps Script code.gs file:
function doPost(e) {
if(typeof e !== 'undefined')
return ContentService.createTextOutput(JSON.stringify(e.parameter));
}
If I make a request using fetch from the background.js of my Chrome extension and include the id parameter in the URL, I get the expected result.
const url = 'https://script.google.com/.../exec?id=123';
fetch(url)
.then(response => response.text())
.then(data => { console.log(data) }) // {"id":"123"}
Instead of writing id as a parameter in the URL, I would like to make the request using the POST method.
I tried to use the object below, but I don't know how to include the variable I want to send:
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: {}
}
I believe your goal is as follows.
You want to send the value of id=123 with the request body instead of the query parameter.
In this case, how about the following modification?
Google Apps Script side:
function doPost(e) {
if (typeof e !== 'undefined') {
const value = JSON.parse(e.postData.contents); // This is the value from the request body.
return ContentService.createTextOutput(JSON.stringify(value));
}
}
Javascript side:
const url = "https://script.google.com/macros/s/###/exec";
const data = { id: 123 };
fetch(url, { method: "POST", body: JSON.stringify(data) })
.then((res) => res.text())
.then((res) => console.log(res));
By this modification, you can see the value of {"id":123} in the console.
Note:
When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script (Author: me)
To include the data you want to send in the request body and to make a POST request using the fetch function, you can do the following:
const data = {id: '123'};
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.text())
.then(data => { console.log(data) })
This send a POST request to the URL with data in the request body. The server-side function (in this case, doPost) will receive the data in the e.parameter object.
I hope this helps you.
I am trying to use the graphbrainz library on a React app with fetch API, but however I format my request body, this error shows:
BadRequestError: Must provide query string. at graphqlMiddleware (C:\Users\User\Desktop\project\node_modules\express-graphql\index.js:76:44) at processTicksAndRejections (internal/process/task_queues.js:95:5)
The call is being made like this:
let myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
const raw = "{ \"query\": \"{ lookup { releaseGroup(mbid: \\\"99599db8-0e36-4a93-b0e8-350e9d7502a9\\\") { title } }}\"}";
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
mode: 'no-cors'
};
fetch("http://localhost:3000", requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I have tried making the same call on Postman and cURL and it works successfully.
The graphbrainz instance is being run as a standalone node server.
Can anyone guide me how to proceed with this or what am I doing wrong? I have exhausted almost all stackoverflow questions and GitHub threads. I have the idea that it must be the bodyParser on the express-graphql server that it is causing this, but I can't see how to change/modify it since it comes from the package I am using.
I think you might be escaping inner quotes in the query incorrectly. Try replacing \"99599db8-0e36-4a93-b0e8-350e9d7502a9\" with \\\"99599db8-0e36-4a93-b0e8-350e9d7502a9\\\".
Can you try to stringify your body payload before sending it.
const raw = JSON.stringify({
"query": "{ lookup { releaseGroup(mbid: \"99599db8-0e36-4a93-b0e8-350e9d7502a9\") { title } }}"
});
doing this will stringify your payload to
"{\"query\":\"{ lookup { releaseGroup(mbid: \\\"99599db8-0e36-4a93-b0e8-350e9d7502a9\\\") { title } }}\"}"
I'm trying to access the returned content-type from my GET request so I can decide the kind of preview I want to like for html maybe pass through an iframe and for a PDF maybe some viewer. The problem is when I do console.log(response.headers) the object returned doesn't have content-type in it but when I check the networks tab the response headers has content-type:html/text. How can I get the content-type from the response headers?
this is how my GET request looks like
const getFile = async () => {
var requestOptions = {
method: "GET",
headers: context.client_header,
redirect: "follow",
};
let statusID = context.currentStatus.ApplicationID;
var response = await fetch(
process.env.REACT_APP_API_ENDPOINT +
"/services/getStatus?ApplicationID=" +
statusID,
requestOptions
);
console.log(response.headers);
if (response.ok) {
let fileHtml = await response.text();
setfileURL(fileHtml);
} else {
alert.show("Someting went wrong");
}
};
The Headers object isn't a great candidate for console.log() since it is not easily serialisable.
If you want to see everything in it, try breaking it down to its entries via spread syntax
console.log(...response.headers)
You'll probably find that you can in fact access what you want via
response.headers.get("content-type")
See Headers.get()
i'm trying to use this website: https://rel.ink/,
to implement a link-shortener in my webapp,
i can successfully POST a request, but what i GET back is the same object, not a shortened version.
I know it's basic stuff but i can't wrap my head around it.
The website states that i need to send more information with my GET request, but the GET requests should not contain a body yes?
Here's my code:
async function fetchNewLink() {
let newLinkJson = await postLink(input.value)
let newLink = await getShortLink(newLinkJson)
console.log(newLink)
}
function postLink(input) {
return fetch('https://rel.ink/api/links/', {
method: 'POST',
body: JSON.stringify({
url: input
}),
headers: {
"Content-type": "application/json"
}
})
.then(response => response.json())
.then(json => json)
}
function getShortLink(response) {
return fetch('https://rel.ink/api/links/' + response.hashid)
.then(result => result.json())
.then(newLink => newLink)
}
Many thanks
If what you're trying to get is the shortened version of the link, the API does not return exactly that when you make a request. However, all you need is the hashid it returns. The shortened link is the main website's url(https://rel.ink) concatenated with the hashid.
So if the API returns nJzb3n as the hashid when you make a POST request, the shortened link would be https://rel.ink/nJzb3n
I hope that helps.
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