MIcrosoft API get Calendar Event description and show it appropriately - reactjs

In my React project, I made an Axios call to populate a Calendar Event List taking data from Microsoft Outlook Calendar (using Microsoft API). The result is the following
As you can see only event description give me a problem. Indeed to show the event description it shows me an HTML string without the event detail.
I read that I have to put in the header of my request Content-type:text, but I tried and It doesn't work. How I can solve that? This is my Axios Request
getEvents(startDate, endDate, accessToken) {
const startDateString = startDate.toISOString();
const endDateString = endDate.toISOString();
axios.get(
`https://graph.microsoft.com/v1.0/users/${USER_PUBLIC_ID}/calendarview?startdatetime=${startDateString}&enddatetime=${endDateString}&orderby=start/dateTime`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
},
).then(response => this.setEvents(response.data.value))
.catch((error) => {
console.error(error.response);
});
}

For that matter Prefer: outlook.body-content-type="text" header needs to be specified.
According to documentation:
To specify the desired format to be returned in the Body and
UniqueBody properties in a GET request, use the Prefer: outlook.body-content-type header:
Specify Prefer: outlook.body-content-type="text" to get a message body returned in text format.
Specify Prefer: outlook.body-content-type="html", or just skip the header, to return the message body in HTML format.
Example
getEvents(startDate, endDate, accessToken) {
const startDateString = startDate.toISOString();
const endDateString = endDate.toISOString();
return axios.get(
`https://graph.microsoft.com/v1.0/users/${USER_PUBLIC_ID}/calendarview?startdatetime=${startDateString}&enddatetime=${endDateString}&orderby=start/dateTime`,
{
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Prefer' : 'outlook.body-content-type="text"'
}
}
);
}

You need to give axios a config object. Currently, you are using the get property, that is why your code doesn't work currently:
axios({
url: `https://graph.microsoft.com/v1.0/users/${USER_PUBLIC_ID}/calendarview?startdatetime=${startDateString}&enddatetime=${endDateString}&orderby=start/dateTime`,
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-type": "text"
},
})
You can read more here: https://github.com/axios/axios

Related

How to upload multi image in api?

const addProdFunc = () => {
const proheader = {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${token}`,
};
axios
.post(
process.env.REACT_APP_ADMIN_API_URL + "product/",
{
image_path: pimg,
product_img: simg[0],
},
{
headers: proheader,
}
)
.then((response) => {
console.log(response);
});
};
I tried a single image it works but when I try to upload multiple images it doesn't upload.
when I put in the console image data comes like this.
same code for both fields in the backend.
You need to make sure that your API expects one or more images. You seem to get the images correctly from the front-end side but the back-end is not expecting that.

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.

axios post request without body getting to the server without the headers

the request getting to the server without the headers:
const res = await axios.post(`/api/follow/${props.match.url}`, {
headers: {
Authorization: `Bearer ${token}`,
userId: userId,
},
});
anyone knows why?
should just put null in the body place, and it works

How to pass authentication token with every React request to back end API?

I have an existing application in which REST APIs are already developed. I am thinking to develop a front end using React JS and front end should call my REST APIs with every request.
However when I login to my application then a token is generated which is passed to every subsequent requests as an authentication header. How can I achieve this using React?
I am a beginner in React.
You can use axios as a library, and add this as a configuration
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
https://www.npmjs.com/package/axios
Use fetch. Example:
var data = {myData: 'hello'}; // or just 'hello'
fetch(YOUR_URL, {
method: 'POST', // or GET
body: JSON.stringify(data), // data can be string or object
headers:{
'Authorization': YOUR_TOKEN,
// ... add other header lines like: 'Content-Type': 'application/json'
}
}).then(res => res.json()) // if response is json, for text use res.text()
.then(response => console.log('Response:', JSON.stringify(response))) // if text, no need for JSON.stringify
.catch(error => console.error('Error:', error));
First receive the token and save it to your browsers local storage using localStorage.setItem('token', JSON.stringify(userToken));
Then, everytime you send a request, you get this token from your local storage using localStorage.getItem("token")
Thereafter, if you were POSTing an object with a key value of ID: 1, you would do:
await fetch("your_API_endpoint", {
method: 'POST',
headers: { 'Content-Type': 'application/json', "Authorization": localStorage.getItem("token") },
body: JSON.stringify({'ID': '1'})
})

Setting authorization header in Fetch API

I have a Node/Express backend and I'm consuming the API with a React Client. I want to be able to set the authorization header after a user is signed up. This ensures that subsequent requests are sent with the authorization header.
I can see how it's done in Axios here and how to retrieve the authorization header in Fetch here
Is it possible to do this with Fetch API and how?
Thank you in advance.
var url = "https://yourUrl";
var bearer = 'Bearer ' + bearer_token;
fetch(url, {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
'Authorization': bearer,
'X-FP-API-KEY': 'iphone', //it can be iPhone or your any other attribute
'Content-Type': 'application/json'
}
}).then(responseJson => {
var items = JSON.parse(responseJson._bodyInit);
})
.catch(error => this.setState({
isLoading: false,
message: 'Something bad happened ' + error
}));
As far as I know, there's no way to use default options/headers with fetch. You can use this third party library to get it to work, or set up some default options that you then use with every request:
// defaultOptions.js
const defaultOptions = {
headers: {
'Authorization': getTokenFromStore(),
},
};
export default defaultOptions;
Then use the default options like:
import defaultOptions from './defaultOptions';
// With default options:
fetch('/auth', defaultOptions);
// With additional (non-default) options:
fetch('/auth', { ...defaultOptions, body: JSON.stringify(additionalData) });
You can pass headers as second parameter of fetch:
fetch(<your url>, {
headers: {
authorization: <whatever is needed here>
}
})
headers: {
'Authorization': `Bearer ${localStorage.getItem("token")}`,
'Accept': 'application/json',
'Content-Type': 'multipart/form-data;
},
In my case, the problem was that the string I was setting as the Authorization was not yet generated. I had to wrap it in a promise, and suddenly it worked.
let authHeader: string = await SearchAuthService.getAuthHeader();

Resources