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);
        }
      });
12
  • What is your backend framework? Commented Aug 9, 2021 at 5: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? Commented Aug 9, 2021 at 5:11
  • use query-string package wich is parse and stringify URL query strings Commented Aug 9, 2021 at 5:23
  • See stackoverflow.com/a/14551320/11895568 Commented Aug 9, 2021 at 5: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. Commented Aug 9, 2021 at 5:36

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

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=&quot;&lt;p&gt;Hello World!&lt;/p&gt; &quot;) 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(/&lt;/g, '<').replace(/&gt;/g, '>'); But it's still showing the same error.
It's because of the <p>Hello World</p> 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.
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.