getting data with fetch is working but not with axios - reactjs

I can get my data with fetch
let myHeaders = new Headers();
myHeaders.append('X-Auth-Token', token,);
myHeaders.append('Content-Type', 'application/json');
fetch("myUrl", {
withCredentials: true,
headers: myHeaders
}).then(function (response) {
console.log(response)
})
but fetching data is not working with axios. this is my axios code
const headers={
'X-Auth-Token': token,
"content-type":"application/json"
}
axios.get('myUrl',{headers:headers,withCredentials:true})
.then(response => {
console.log(response)
})
.catch(err => {
console.log(err)
});

I use it this way:
Check if your headers object is in good shape with a console log.
const headers = {
'X-Auth-Token': token,
'content-type': 'application/json'
};
console.log(headers);
const request = axios.create({
myUrl,
headers: myHeaders,
withCredentials: true
})
request.get() // If you add a string inside the brackets it gets appended to your url
.then(res => console.log(res))
.catch(err => console.log(err))
If the error you are getting is about CORS (Cross Origin Resource Sharing):
If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol, domain, port.
You need to set the server to allow your origin.
It's a very common problem and you will see it happen often. Read more about cors here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Related

React: Can't pass an id to an endpoint in order to display an image

I'm quite new to react and have an issue that i'm not sure whats wrong.
I have one external api with an endpoint that contains articles and another endpoint to get the images thats connected with the articles. I want to display the articles and the images together, but I can't get the images to show.
The flow is as follows:
First I find the article with the article api endpoint and the article id. And it looks like this:
const { itemId } = useParams()
const [article, setArticle] = useState([])
const [articleImg, setArticleImg] = useState('')
const [fileId, setFileId] = useState('')
useEffect(() => {
fetch(`https://api.fortnox.se/3/articles/${itemId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
console.log(data)
setArticle(data.Article)
console.log(data)
})
}, [itemId])
In order to get the image to that article I have to find a FileId by searching the article number against ArticleFileConnections endpoint:
(Documentation)
useEffect(() => {
fetch(`https://api.fortnox.se/3/articlefileconnections/?articlenumber=${itemId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
setFileId(data.ArticleFileConnections[0].FileId)
console.log(data.ArticleFileConnections[0].FileId) // Prints an id-number in the console
})
}, [])
When I have the FileId I use it with another endpoint called Archive in order to get the image. Documentation That fetch looks like this:
useEffect(() => {
fetch(`https://api.fortnox.se/3/archive/${fileId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
setArticleImg(data)
console.log(data) // Prints an object thats a folder structure with an empty array
})
}, [])
I tried to change the ${fileid} to the actual id-number in the archive endpoint like this
https://api.fortnox.se/3/archive/8c05c536-c110-402d-82da-60f25f6b0e1c Then I get this error message in the console:
Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0
But I don't get that error if I pass the ${fileid} in the endpoint https://api.fortnox.se/3/archive/${fileid} Although when I console.log the state fileId that I pass in it prints the fileId-number.
So what I expect is that the fileId-state that I use in the archive endpoint should display an image by writing this code.
<div>
<img src={articleImg} alt="product" />
</div>
I hope all this is understandable and I hope someone can help me with what i'm doing wrong.
Thank you.
Note: It all works in postman. When I try the endpoints like the flow above it shows the image with this endpoint https://api.fortnox.se/3/archive/8c05c536-c110-402d-82da-60f25f6b0e1c
Your useEffect for fetching the fileId is behaving as a componentDidMount. What you want instead is a componentDidUpdate behavior, which you can do by
useEffect(() => {
fetch(`https://api.fortnox.se/3/archive/${fileId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
setArticleImg(data)
console.log(data) // Prints an object thats a folder structure with an empty array
})
}, [fileId]) // Notice the change here. It ensures that the useEffect is called every time the fileId is updated.

How to send body data and headers with axios get request?

I've tried
axios.get(url, {headers:{},data:{}})
But it doesn't work with this.
You should refer to https://github.com/axios/axios#request-config
Check the section for data and header.
As far as I know you can't send body data with GET request. With get you can have only Headers. Just simply change to POST and then you can do something like this :
const bodyParameters = {
key: "value",
};
const config = {
headers: { Authorization: `Bearer ${userToken}` },
};
axios.post("http://localhost:5000/user", bodyParameters, config)
.then((res)=> {
console.log(res)
})
.catch((err) => console.log(err));
};
or if you want to send headers with GET request
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
// data is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
https://stackoverflow.com/a/54008789
yeah, it's true it doesn't work to send body in Axios get even if it works in the postman or the backend.
You can try this:
const getData = async () => {
try {
const response = await axios.post(`https://jsonplaceholder.typicode.com/posts`, {
method: 'POST',
body: JSON.stringify({
id: id,
title: 'title is here',
body: 'body is here',
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json));
console.warn(response.data);
} catch (error) {
console.warn(error);
}
}
You can send data in a get request by using the config object and the params option of the config object. This is a workaround and it works, but on the server the data sent is available as request.query not as request.body. Based on the example below you would access your params data on your server using request.query.user_id. It should be noted that using this method will also append the params to your request url which could have unintended consequences based on your specific situation. For example, the url for the request below would be sent as example.com?user_id=1234. You can read more about the axios request config here.
axios.get(
'example.com/',
{
params: { user_id: 1234 },
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
},
);

How to resolve "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource" [duplicate]

This question already has an answer here:
Calling Yelp API from frontend JavaScript code running in a browser
(1 answer)
Closed 2 years ago.
I am trying to make a fetch request for my React app, but I keep getting this CORS error. The request works fine in Postman. I have added the Access-Control-Allow-Origin header. I also tried adding mode: 'no-cors', but that did not work either. I can't find anything online for any other solutions. This is the code I'm using:
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer <MY_API_KEY>");
myHeaders.append("Cookie", "__cfduid=db290300ecfe95ec1fe3bc92c388c3c991586618117");
myHeaders.append("Access-Control-Allow-Origin", "*");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("https://api.yelp.com/v3/businesses/search?location=Houston", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
If you're simply looking to validate the Yelp api response then try running the request through a proxy that deals with the CORS policy for you like this:
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer <MY_API_KEY>");
myHeaders.append("Cookie", "__cfduid=db290300ecfe95ec1fe3bc92c388c3c991586618117");
myHeaders.append("Access-Control-Allow-Origin", "*");
var proxyUrl = 'https://cors-anywhere.herokuapp.com/'
var targetUrl = 'https://api.yelp.com/v3/businesses/search?location=Houston'
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch(proxyUrl + targetUrl, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
The Access-Control-Allow-Origin is response header, it's mean that it does not matter in request, the server should allow to you make request.
is it API at yelp.com is allowed to you?

Fetch request infinite pending in a new tab in Chrome

In my react project Chrome will never send fetch requests if I open a link in a new tab:
chrome network tab
chrome console tab
Here is standard fetch:
let h = new Headers();
h.append('Accept', 'application/json');
h.append('Content-Type', 'application/json');
h.append('X-Custom-Header', '123');
let req = new Request(url, {
method: 'GET',
headers: h, //заголовки
mode: 'cors'
});
fetch(req).then((response) => {
if(!response.ok) {
console.log(response);
}
return response;
})
.then((response) => response.json())
.then((items) => console.log(items.data))
I tried to do this in dev console:
async function load() {
let response = await fetch('/somesite.com', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Custom-Header': '123'
},
mode: 'cors'
});
let data = await response.json();
console.log(data);
}
load();
XHR requests doesn't work too. Console log is clean, no mistakes. In Mozilla/Opera/Safari everything is fine.
With disabled chrome://flags/#out-of-blink-cors Chrome will send requests correctly. But it doesn't solve issue for all users.
Access-Control-Allow-Origin set correctly.
I don't understand what is wrong...
Useful links:
https://support.google.com/chrome/thread/11089651?hl=en
https://www.chromestatus.com/feature/5768642492891136
https://www.chromium.org/Home/loading/oor-cors

Post data with By posting data with 'content-type': 'application/x-www-form-urlencoded' and 'key': 'key'

I want to post data to the server using headers content-type: 'application/xww-form-urlencode' but it fails because of the content type change to application/json
var headers= {
'content-type': 'application/x-www-form-urlencoded',
'x-access-key': 'key'
}
var data = {
'twins' : twins
}
axios.post('url', data, { headers: headers })
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
With Postman I successfully added the entry
In your headers change content-type to
'Content-Type': 'application/x-www-form-urlencoded'
If this doesn't work, then you I feel you might be using an interceptor. Which might be overriding your configuration.

Resources