0

I am trying to post data from React component to spring boot controller.

I sent xhr requests like this, which failed with 400:

const valToSent = {
  queueId: this.props.queueId,
  flag: restFlag //value is '' or '1'
};

const xhr = new XMLHttpRequest();
xhr.open('post', '/display/clickNext.json', true);
xhr.setRequestHeader('Content-Type', 'application/json');
const data = JSON.stringify(valToSent);
xhr.send(data);

Then I tried this, which worked:

const xhr = new XMLHttpRequest();
xhr.open('post', `/display/clickNext.json?queueId=${this.props.queueId}&flag=${restFlag}`, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send();

But I don't know why.n what is the difference between them?

I searched and found this question what's the difference between request payload vs form data as seen in chrome, if I understand it right, the best answer tells 'they differ in the Content-Type but not in the way data is submitted', so I am more confused why I am wrong and failed.

I really want to understand this problem, the template literals seem not so elegant by using it this way, more important, it seemed like it is about some basic concepts.

GLPease
  • 545
  • 1
  • 8
  • 19
  • How are you trying to read the value on the server side? – Patrick Evans Sep 19 '17 at 06:31
  • I don't really know, the controller is written by the back-end engineer, and I do not understand Java. @RequestMapping("/clickNext") public Map clickNext(@RequestParam String queueId, @RequestParam String flag) { Map model = resttemplate.postForObject(queueConfig.getCommondUrl() + "clickNext.json?queueId={queueId}&flag={flag}", null, Map.class, new Object[] { queueId, flag }); return model; } – GLPease Sep 19 '17 at 06:35

1 Answers1

0

The first one is a sensibly arranged POST request that says it is sending JS in the body and sends JSON in the body.

The second one is … weird. It says it is sending Form Encoded data in the body, but actually sends nothing in the body while shoving the data (without proper escaping) into the query string.

To tell why the sensible request is getting a "400 Bad Request" error from the server would require that you debug the server side code.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335