How to make a fetch request to TinyURL? - javascript

I am trying to make a fetch request specifically a post request to tinyURL to shortern a url generated on my site. here is the tinyURL API
Currently, I am writing my code like this but it doesn't appear to be returning the short url.
the word tinyurl seems to be banned within links so all links
containing the word tinyurl have been replaced with "SHORT"
here is the tinyURL API https://SHORT.com/app/dev
import * as React from 'react'
interface tinyURlProps { url: string } export const useTinyURL = ({ url }: tinyURlProps) => { React.useEffect(() => {
const apiURL = 'https://api.SHORT.com/create'
const data = JSON.stringify({ url: url, domain: 'tiny.one' })
const options = {
method: 'POST',
body: data,
headers: {
Authorization:
'Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
Accept: 'application/json',
'Content-Type': 'application/json',
},
} as RequestInit
fetch(apiURL, options)
.then((response) => console.log(response))
.then((error) => console.error(error))
console.log('TinyUrl ran') }, [url])
}

The snippet below seems to work
const qs = selector => document.querySelector(selector);
let body = {
url: `https://stackoverflow.com/questions/66991259/how-to-make-a-fetch-request-to-tinyurl`,
domain: `tiny.one`
}
fetch(`https://api.tinyurl.com/create`, {
method: `POST`,
headers: {
accept: `application/json`,
authorization: `Bearer 2nLQGpsuegHP8l8J0Uq1TsVkCzP3un3T23uQ5YovVf5lvvGOucGmFOYRVj6L`,
'content-type': `application/json`,
},
body: JSON.stringify(body)
})
.then(response => {
if (response.status != 200) throw `There was a problem with the fetch operation. Status Code: ${response.status}`;
return response.json()
})
.then(data => {
qs(`#output>pre`).innerText = JSON.stringify(data, null, 3);
qs(`#link`).href = data.data.tiny_url;
qs(`#link`).innerText = data.data.tiny_url;
})
.catch(error => console.error(error));
body {
font-family: calibri;
}
<p><a id="link" /></p>
<span id="output"><pre/></span>

Related

Getting erorr Cannot POST /undefined/signup

I can sign up a user via postman. But when I use my app I am getting that error. My signup method is ok. But my fetch address is not good. here is method.
export const signup = user => {
return fetch(`${API}/signup`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err => {
console.log(err);
});
};
const API = process.env.REACT_APP_API_URL;

Passing api key for all API automatically

How to set api key for all API on reactjs/javascript?.I have problem with that
I think it all boils down to the default headers for each request. Personally I would go like this
const defaultHeaders = {
"Authorization": "Bear --some-secret-token--",
"Content-Type": "application/json"
}
const get = (url, params, headers) => {
return fetch(
url,
{
method: "GET",
headers: {
...defaultHeaders,
...headers,
}
}
)
.then(response => response.json())
};
const post = (url, body, headers) => {
return fetch(
url,
{
method: "POST",
body: JSON.stringify(body),
headers: {
...defaultHeaders,
...headers,
}
}
)
.then(response => response.json())
};
get('https://jsonplaceholder.typicode.com/todos/1');
post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1,
});
I export ready-to-use methods to cover some default headers.
If you use Axios, you can do like how #crashmstr suggested. But if you use regular fetch, this is definitely not a bad idea.

my post request get response as https but does not return to a new page (javascript)

I'm send a post request and I get the response like this
" [Symbol(Response internals)]: {
url: 'https://login.somenewloginpage'}"
and what I want to do is I want to open a new page via that url but it does not direct to the new page.
const login= () => async () => {
const api = `somePostRequest`
fetch(api, {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-url-encoded',
Accept: 'application/json',
},
})
.then(function(res) {
return res //maybe I should do something in this part...
})
.then(data => console.log(data));
};
Here's how to use fetch() with async/await syntax :
const login= () => async () => {
const api = `somePostRequest`;
const response = await fetch(api, {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-url-encoded',
Accept: 'application/json',
},
});
const data = await response.json(); // { url: 'https://login.somenewloginpage'}
window.location.replace(data.url); // <-- Redirection
};

axios post method 400 bad request

I'm getting a JSON file, editing it and trying send it back to server. But when I use post method it throws an error 400 bad request.In response shows "no template_id or no template_json presented". What could be the problem?
saveData() {
const { data } = this.state
let token = localStorage.getItem("token")
axios
.post(
"http://dev.candidates.hrmessenger.com/stage/set-template",
data,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
},
)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
Please try to use this:
data.template_id = 1;
saveData() {
const { data } = this.state
data.template_id = 1;
let token = localStorage.getItem("token")
axios
.post(
"http://dev.candidates.hrmessenger.com/stage/set-template",
data,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
},
)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
You missed the parameter template_id, or you need to ask from your API developer to send the documentations of the POST Method API.

React Native "fetch" returning server response without the information

I am using react native to create an application to act as a website that currently exists (with a user interface that works on a phone). i am using the "fetch" method to send a Http POST request to get information from a web server. The web server sends a response but it doesn't include the response message:
I apologies that is an image but the debugger is not working for me.
The code used to send the request:
HttpRequest = (RequestURL, callback) => {
var AdminLoginBindingModel = {
usr: this.state.username,
pwd: this.state.password,
}
fetch(RequestURL,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then((res) => {
callback(res);
})
.catch((error) => {
this.setState({Response: "Error: " + error});
})
}
The callback function in the parameters is just a function to change the state variable to display the information on the screen
ValidateResponse(response){
this.setState({Response: "Result: " + JSON.stringify(response),
displayMessage: "Success"});
console.log(JSON.stringify(response));
}
The Request being sent is "https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd="
The server responds with a json object regardless of a correct login or not
Edit:
Changing the response to
.then((res) => {
callback(res.json());
})
Result:
To get object from fetch response, you have to call res.json like following:
fetch(RequestURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then(res => res.json()) // HERE
.then(obj => callback(obj))
But it occurs an error because response body itself is invalid json format. It contains some HTML tags:
{"member": {"username":"","password":"","key":"***","status":"No"}}<br><br>Username: <br>Key: ***
Please check the inplementation of server.
EDIT: full code here
const fetch = require("node-fetch")
HttpRequest = (RequestURL, callback) => {
const AdminLoginBindingModel = { usr: "foo", pwd: "bar" }
fetch(RequestURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then(res => res.json())
.then(obj => callback(obj))
.catch(error => console.log(error))
}
const ValidateResponse = response => console.log(JSON.stringify(response))
URL = 'https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd='
HttpRequest(URL, ValidateResponse)
response doesn't contain received data directly. It provides interface methods to retrieve it. For example use response.json() to parse response text as JSON. It will return promise that resolves to the parsed object. You won't need to call JSON.parse on it:
fetch(RequestURL,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then((res) => {
return res.json();
}).then((obj) => {
console.log(obj);
});
Check https://developer.mozilla.org/en-US/docs/Web/API/Response and https://facebook.github.io/react-native/docs/network.html for more information.

Categories

Resources