React JS Fetch from multiple URLs - javascript

I can fetch contents from my Django server with which code below.
But i need fetch from also another URL : http://127.0.0.1:8000/userpost/tagpool/
I don't know how to do. Please help.
useEffect(() => {
fetch("http://127.0.0.1:8000/api/contents/", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token xxxxxxxxxxxxxx'
}
})
.then( resp => resp.json())
.then( resp => setFeatured(resp))
.catch( error => console.log(error))
}, [])

Use Promises chaining or Chaining
For example,
// Make a request for user.json
fetch('http://localhost/article/promise-chaining/user.json')
// Load it as json
.then(response => response.json())
// Make a request to GitHub
.then(user => fetch(`https://api.github.com/users/${user.name}`))
// Load the response as json
.then(response => response.json());

Related

Why is JSON data sent from server to browser undefined?

I want to make a request to my server with fetch(), and have data returned to be used in the front end app.
here is my route:
app.get('/game-data', (req, res) => {
res.json({ data: "test-data" })
})
and here is my request:
button.addEventListener('click', () => {
fetch('/game-data', {
headers: {
'accept': 'application / json',
'Content-Type': 'application/json'
}
})
.then(response => {
console.log(response)
response.json()
})
.then(myJson => {
console.log(myJson)
})
})
I can see the response object in the first console log, but response.json(), or response.text() are returning undefined.
Please help me see what I am missing!
You need to return the value to use it in another .then
.then(response => {
console.log(response)
return response.json()
})

POST request generates failed to fetch

I'm having problems making a POST request through the fetch API from javascript and I get the following error: TypeError: Failed to fetch at fetchCallImpp at window.fetch
The code is the following:
const agregarCafetalDB = (nombre) => {
const data = {
"nombre": `${nombre}`,
};
const requestOptions = {
method: 'POST',
body: JSON.stringify(data),
redirect: 'follow',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
};
fetch(url, requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
btnAgregar.addEventListener('click', (e) => {
agregarCafetalDB(cafetal.value)
});
I would like you to help me solve the error thank you very much in advance
Does the same error shows in other browsers? fetch is ES6 Javascript, maybe the browser you are using doesn't support it.
fetch(url, requestOptions)
Also, make sure that variable 'url' is defined.

Using variable from client API callback in node backend

If I make a request on client side using the code below
public/foo.js
function bar() {
fetch('https://api.github.com/')
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(error => console.error(error))
}
how can I send the data variable to node backend?
/app.js
app.get("/", cors(), (request, response) => {
response.render('index.html');
})
It is my understanding that you are trying to fetch data from the URL that is not handled by your server-side on your client-side and send that data back to your own server-side.
On your server-side, create a new POST method:
app.post("/example", cors(), (request, response) => {
let body = request.body;
response.json(body);
})
On your client-side, send a new POST request:
function postExample(data) {
return fetch(`http://localhost:YOURPORT/example`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
}
Replace YOURPORT with your server's port. And make a call to the postExample:
function bar() {
fetch('https://api.github.com/')
.then(response => response.json())
.then(data => {
postExample(data).then(res => res.json())
.then(console.log(res));
})
.catch(error => console.error(error))
}

How to use ContextualWeb News API in node.js using axios HTTP client?

I am trying to integrate ContextualWeb News API in a node.js application.
In particular, I would like to use axios with parameters to make the GET request to the news API endpoint.
The following code works but it uses fetch and the parameters are embedded in the url which is inconvenient:
const url ="https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI?autoCorrect=false&pageNumber=1&pageSize=10&q=Taylor+Swift&safeSearch=false"
const options = {
method: 'GET',
headers: {
"X-RapidAPI-Host": "contextualwebsearch-websearch-v1.p.rapidapi.com",
"X-RapidAPI-Key": "XXXXXXXX"
},
}
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e))
How can the code be converted to work with axios? The ContextualWeb news API should return a resulting JSON with the related news articles.
This approach should work:
const axios = require("axios");
const url = "https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI";
const config = {
headers: {
"X-RapidAPI-Host": "contextualwebsearch-websearch-v1.p.rapidapi.com",
"X-RapidAPI-Key": "XXXXXX" // Replace with valid key
},
params: {
autoCorrect: false,
pageNumber: 1,
pageSize: 10,
q: "Taylor Swift",
safeSearch: false
}
}
axios.get(url, config)
.then(response => console.log("Call response data: ", response.data))
.catch(e => console.error(e))

Error in calling POST api in react native by handling action in redux

i am fetching some data by using POST api call in which i have data and a token value for header, but i am getting bad response and i checked many docs but can't figure out the error, here is the code:
export const shareUserProfileHandler = (sharedReceiverData) => {
return dispatch => {
let formData = new FormData();
for (let key in sharedReceiverData) {
formData.append(key, sharedReceiverData[key]);
}
let requestConfig = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': 'Token 97a74c03004e7d6b0658b14ddb'
},
body: formData
};
fetch(`http://api.com`, requestConfig)
.then(response => response.json())
.then(response => {
alert('share user card api worked')
})
.catch(error => {
alert('api error ' + error)
})
}
};
the above is catching error and showing - SyntaxError: JSON Parse error: Unrecognized token'<'
Your response doesn't seem to be a JSON.
Replace
.then((response) => response.json())
For
.then((response) => { console.log('response', response); response.json() })
And check what is wrong with the response before the error.

Categories

Resources