Search code examples
reactjsaxiosgoogle-apigoogle-calendar-apigoogle-authentication

Axios put events Google Calendar api with React


I want to insert an event using axios post request. This is the code:

async function inserisciTurni() {
axios.post(`https://www.googleapis.com/calendar/v3/calendars/${calendarioselezionato}/events`, {
  calendarId: `${calendarioselezionato}`,
  resource: evento,
  headers: {
    authorization: `Bearer ${accessToken}`,
  },

}).then((result) => { console.log(result) })


var evento = {
"summary": "Titolo prova evento",
"description": "prova evento",
"start": {
  "dateTime": "2022-08-28T09:00:00-07:00",
},
"end": {
  "dateTime": "2022-08-28T17:00:00-07:00",
}  };

But I receive this error:

IMAGE ERROR 401


Solution

  • I thought that in your script, your request body is correct. But, I thought that it is required to modify the method for requesting. So, in your script, how about the following modification?

    Modified script:

    async function inserisciTurni() {
      var accessToken = "###"; // Please set your access token.
      var calendarioselezionato = "###"; // Please set your calendar ID.
    
      var evento = {
        "summary": "Titolo prova evento",
        "description": "prova evento",
        "start": {
          "dateTime": "2022-08-28T09:00:00-07:00",
        },
        "end": {
          "dateTime": "2022-08-28T17:00:00-07:00",
        }
      };
      var res = await axios.post(
        `https://www.googleapis.com/calendar/v3/calendars/${calendarioselezionato}/events`,
        JSON.stringify(evento),
        {headers: {authorization: `Bearer ${accessToken}`, "Content-Type": "application/json"}}
      );
      console.log(res.data);
    }
    

    Note:

    • When I tested this modified script, I could confirm that an event could be created in my Calendar.

    References: