2

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);
        }
      });
Lance
  • 215
  • 1
  • 6
  • 21
  • What is your backend framework? – negin motalebi Aug 09 '21 at 05:05
  • 3
    Are you supposed to be sending the data in query parameters as in the first example? Or are you supposed to be sending a json body? – im_baby Aug 09 '21 at 05:11
  • use _query-string_ package wich is parse and stringify URL query strings – Rahul Aug 09 '21 at 05:23
  • See https://stackoverflow.com/a/14551320/11895568 – ale917k Aug 09 '21 at 05:29
  • My backend is MySQL and I'm supposed to be sending the data in query parameters (now I know what it's called). So I'm doing the wrong thing the whole time by sending as a json body. – Lance Aug 09 '21 at 05:36
  • The error suggests you might need to look at [URL encoding](https://www.w3schools.com/tags/ref_urlencode.ASP) the values you're sending in the query parameters. – j-petty Aug 09 '21 at 06:49
  • It's weird, I've encoded my HTML and it fixed this error but it now has error 500 even though the insert works when I copied and pasted the URL+params from the console error. – Lance Aug 09 '21 at 11:48
  • A 500 error (should) indicates an error on the backend. Looks like the POST is fixed, now you should look at the API and why it can't process the request. – im_baby Aug 09 '21 at 13:14
  • But if directly copy pasting the API URL+params in the browser works, does it still means that the backend has the error? – Lance Aug 09 '21 at 13:28
  • A browser performs a GET request when it requests a url. POST typically happens for form events or other client-side JS. I suspect you're supposed to use GET. – im_baby Aug 09 '21 at 13:34
  • 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. I've posted the .ajax code in my post above. – Lance Aug 09 '21 at 13:52
  • @im_baby I've tried using GET request as a last resort and it worked perfectly, thanks a lot! – Lance Aug 10 '21 at 01:25

1 Answers1

1

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?

Ikdemm
  • 1,804
  • 1
  • 11
  • 25
  • I've tried the method that you've suggested using axios, which it probably worked, but I'm still getting the same error: A potentially dangerous Request.QueryString value was detected from the client (desc="<p>Hello World!</p> ") I think this is because I'm trying to save html into the db, which I've tried to escape the html tags by using: const desc = htmlContent.replace(/</g, '<').replace(/>/g, '>'); But it's still showing the same error. – Lance Aug 09 '21 at 08:56
  • It's because of the `

    Hello World

    ` value. The API is sending back that response message. If you are in charge of the API, you can deactivate that message. Although it's not that recommended.
    – Ikdemm Aug 09 '21 at 09:19
  • Okay, now that I've encoded the html code with const desc = encodeURIComponent(htmlContent.replace(/'/g, '\'\'')), the POST request still doesn't work when I send the request through the app (getting error 500), but if I copy the parameters and paste it in the browser manually, it actually successfully inserted the event, so is this error related with the axios post method that I've used? **I've posted the POST method that I've used in my original post** – Lance Aug 09 '21 at 09:54