How to send a POST request with variables in React?

Viewed 2199

I am learning how to send a POST request to an API with React.

What I'm trying to achieve right now is sending a POST request to an API. The API will insert the event with something like this (what is this method called?): https://api.com/WebService.asmx/insertEvent?event_id=5&desc=<p>HelloWorld</p>&name=testing

The method that I'm currently using as POST is shown at POST method and it returns me with the error unexpected token '<' in json at position 0 and the result that I get when I console.log(JSON.stringify(event)) is something like this:

{"event_id":"5","desc":"<p>HelloWorld</p>","name":"testing"}```

POST method

const response = await fetch('https://api.com/WebService.asmx/insertEvent', 
         {
             method: 'POST',
             headers: {
                 'Content-Type': 'application/json'
             },
             body: JSON.stringify(event)
        })

Edit: I've fixed the above error by encoding the HTML that I need to send. This is now my latest POST method, but I'm still facing error 500 for some reason even though it works when I copy and pasted the URL+params from the console.log that has the error shown:

const addBulletin = async (event) => {
        console.log(event, '--event')
        const url = 'https://api.com/WebService.asmx/insertEvent';
        axios.post(url, null, { params: {
            title: event.title,
            desc: event.desc,
            image: event.image,
            employee: event.employee,
            entity: event.entity,
            startDate: event.startDate,
            endDate: event.endDate,
            createdBy: event.createdBy
        }})
        .then(response => console.log(response.status))
        .catch(err => console.warn(err));
    };

Edit: I've tested the API on a vanilla JS project using .ajax with POST, and it works, so I think the API shouldn't be a problem.

var json = $('.insert-form').serialize();

$.ajax({
        type: "POST", 
        url: "https://api.com/WebService.asmx/insertEvent",
        data: json,
        async: true,
        success: function (response) {
            alert("Event has been successfully created!");
        },
        error: function (response) {
          console.log(response);
        }
      });
1 Answers

The API you are sending the request to expects a query parameter (data in the URL). https://api.com/WebService.asmx/insertEvent?event_id=5&desc=<p>HelloWorld</p>&name=testing In this request, we are sending 3 query params: event_id, desc, and name.

To send this kind of request from React, you should not use request body. Instead. I advise you to use axios to make it easier. It's a very powerful library, better than using fetch. It should be done this way:

axios.post(`https://api.com/WebService.asmx/insertEvent`, null, { params: {
  event_id: eventId,
  desc
}})
.then(response => response.status)
.catch(err => console.warn(err));

This may help: How to post query parameters with Axios?

Related