POST and GET API Request using fetch, cannot get the data - javascript

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.

Related

`POST` request to script page

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.

Bad Request on accessing Firebase dynamic-links using REST API (using JS)

I'm trying to implement a simple URL shortener using firebase dynamic links via the REST API.
I prepared a simple async JS function for testing (since I don't have a billing account to make external egress calls in cloud functions).
Below is the code:
async function fetcher(keyAPI,tempURL) {
let reqURL=`https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=${keyAPI}`;
let parameters = {
method : "POST",
headers: {
'Content-Type': 'application/json'
},
body : JSON.stringify({
"longDynamicLink": tempURL,
"suffix": {
"option": "SHORT"
}
})
};
await fetch(reqURL,parameters)
.then(res => console.log(res))
.catch(err => console.log(err));
}
I'm recieving a bad request as the response:
Response {
type: "cors", "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[MY_WEB_API_KEY_HERE]",
redirected: true,
status: 400,
ok: false,
statusText: "Bad Request",
headers: Headers,
body: ReadableStream,
bodyUsed: false
}
I need help to debug it.
Try the following after creating a prefix link URL in the firebase console since it is required as a parameter:
let reqURL=`https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=<API_KEY_HERE>`;
let parameters = {
method : "POST",
headers: {
'Content-Type': 'application/json'
},
body : JSON.stringify({
"dynamicLinkInfo": {
"domainUriPrefix": "[PREFIX_URL]",
"link": "[YOUR_LINK]",
},
"suffix": {
"option": "SHORT"
}
})
};
// Get response since it returns pending promise above
return await fetch(reqURL,parameters)
.then(res => res.json())
.catch(err => err);
}
// Fetch from Promise
sURL.then(res => {
console.log(res);
return res;
});
My previous answer was deleted, I don't know why, but its ok
Deleted Post IMG
I faced this problem earlier and some research on it. And it was working. So I took my all code, cleaned it up, and published it on Github, so this doubt can go.
So, Some comments asked How to use this, So here is the answer
You have to add lib from the CDN or self host it, its better to customize the code by yourself for your needs. CDN Link - https://fdl.js.org/src/links.js
Now when you have added the lib, try to call it with this function.
This returns you the shortlink
makefdl(key, st, si, sd, domain, link);
Expression Docs
And You get the shortlink back...
Note: You have to wait for the API to reply, so make a await call, like this
async function links(){
var slink = await makefdl(key, st, si, sd, domain, link);
if(slink != null){
console.log(slink);
// do something here with the shortlink
}
}
<script src="https://fdl.js.org/src/links.js"></script>
If you have any questions then please write down in the comments. I will be happy to answer. :)
For more info about FDljs, visit FDL.js Official Site

Is there an equivalent of `curl -v` in javascript fetch API?

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.

Issues with passing all values entered on a form, via formData, with fetch API

Why formData goes empty to my express+mongodb server? I've some problems with querySelector and addEventListener, but for now thats ok. However, I don't find a way for sending all values of my form to the server. Please, someone help me?
document.querySelector('#enviar-
cadastro').addEventListener('click', Cadastrar);
Cadastrar('http://localhost:5000/usuario/novo')
.then(response => console.log(response.json()))
.then(data => console.log(data))
.catch(error => console.log(error));
function Cadastrar(url) {
const formDados = new FormData(document.querySelector('#signup'))
return fetch(url, {
method: 'POST',
body: JSON.stringify(formDados),
headers: {
"Content-Type": "application/json"
}
})
};
First of all console.log(formDados) inside Cadastrar and see what you get.
This should also help: https://code.lengstorf.com/get-form-values-as-json/

Fetch POST Unexpected end of input Erorr

I'm trying to do a POST request for authentication in Redux and I'm passing email & password as the body but it returns this error in the console:
Uncaught (in promise) SyntaxError: Unexpected end of input
I looked around for the answer and many people suggested that it might be a missing } brace but I looked for it and I don't think it's that.
Here is my fetch function.
export function loginUser(creds) {
let config = {
mode: 'no-cors',
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: `email=${creds.email}&password=${creds.password}`
};
return dispatch => {
dispatch(requestLogin(creds));
return fetch('http://localhost:4000/api/authenticate', config)
.then(response =>
response.json()
.then(user => ({ user, response }))
).then(({ user, response }) => {
if (!response.ok) {
dispatch(loginError(user.message));
return Promise.reject(user);
} else {
localStorage.setItem('id_token', user.token);
dispatch(receiveLogin(user));
}
});
};
}
The fetch POST method calls the API and I see it in the networking tab and I see the response too but the fetch request stops at .then(response => after the url and config.
It's been two days and still can't find the solution. By the way, this works fine in Postman(chrome extension), so nothing wrong with the API.
Thanks
Answer EDIT: The issue was related to CORS, so for anyone having the same issue as I did.
I solve the same question when I remove
mode: 'no-cors'
from the config.
Anyway you could simplify your snippet code to:
fetch('http://localhost:4000/api/authenticate', config)
.then(response => response.json())
.then(({ user, response }) => {
And you should might add catch method to handle an Error object.

Categories

Resources