Reputation: 417
I am trying to run an api in react and have the response returned as a variable. The api returns the title of a given webpage.
DETAILS The api uses the following URL {with a website url appended to the end} http://textance.herokuapp.com/title/
A manual submission of this URL http://textance.herokuapp.com/title/www.antstand.com/ will result in "Antstand the bamboo laptop stand" being displayed in the browser. I am trying to use this api to set variable in my app.
MY CURRENT CODE
async function titleAPI(props) {
const baseUrl = 'http://textance.herokuapp.com/title/'
const response = await fetch(baseUrl + props)
const data = await response
console.log('FUNCTION OUTPUT: ',data)
return data
}
titleAPI(myUrl).then(console.log)
On running the code my unexpected ouptut is below (I was expecting : "Antstand the bamboo laptop stand")
FUNCTION OUTPUT:
Response {type: "cors", url: "http://textance.herokuapp.com/title/www.antstand.com/", redirected: false, status: 200, ok: true, …}
type: "cors"
url: "http://textance.herokuapp.com/title/www.antstand.com/"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers {}
body: (...)
bodyUsed: false
__proto__: Response
I think Cors refers to a cross origin error.
Upvotes: 0
Views: 64
Reputation: 1454
try this way it's display your expecting result "Antstand the bamboo laptop stand" show
const titleAPI=async props =>{
const baseUrl = 'http://textance.herokuapp.com/title/'
const url = baseUrl + props
const response = await fetch(url,{
method:'GET',
mode:"cors",
credentials:"same-origin",
cache:"no-cache",
headers:{
"Content-Type":"application/json",
"Access-Control-Allow-Origin":"*",
},
redirect:"follow",
referrer:"no-referrer"
})
let data = await response.text()
return data
}
titleAPI('www.antstand.com/').then(data=>console.log(data))
Upvotes: 0
Reputation: 1292
body: (...)
and type:'cors'
means you are getting opaque response because of CORS. Either send 'Access-Control-Allow-Origin' to your origin ( or * for all origins ), or configure proxy on frontend to change origin
header of all requests so that server could not receive it as CORS. axios has options to configure proxy. create-react-app also provides mechanism to configure proxy in development environment.
Upvotes: 1