Reputation: 4779
I am working with Amazon's Mechanical Turk, trying to build an ExternalQuestion site which POSTs data back to AMT using a form-- this is the typical method of passing back answers from an ExternalQuestion, mandated by their API.
Very specifically, I am trying to do this in ReactJS, because it has simplified every other aspect of this project.
Is it possible to get React to POST form data without using an external back-end like Flask/python?
This is an important requirement because as far as I can tell from this information (and my own wasted time), using Flask/python will make the POST data look like it is coming from my server, rather than the Worker's browser, and will get rejected.
And yet, when I look through the React documentation on forms I don't even see a discussion of form methods, like GET and POST. I understand that React is going to want this handled by something like an onClick() function, but I can't see any way to do this in React without making the data look like it's coming from my server rather than Worker's browser.
Upvotes: 0
Views: 2649
Reputation: 1638
Form post is just XHR POST with form-data or x-www-form-urlencoded body and get text/HTML returned. This can be done on React with Axios.
This answer show using Axios to send form-data -> https://stackoverflow.com/a/47630754/3849555
Upvotes: 1
Reputation: 661
Your best shot is to use the built in JavaScript Fetch API with the FormData
interface.
For the body you can pass in the payload what you can generate with the FormData interface; MDN's documentation on it:
The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".
Don't use XMLHttpRequest
, fetch is the newer that is built on that.
A Generic example with fetch would look like the following:
const formData = new FormData();
formData.append('username', 'abc123');
formData.append('foo', 'bar);
fetch('https://example.com/foo/bar', {
method: 'POST',
body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', JSON.stringify(response)))
This fetch call then can be called based on a user action like onClick
.
Upvotes: 1