REACT fetch post request

Kamil Lewandowski

I have problem with routing post request I need to build register form and post input from form to mongodb I made router and post route on server side and it works ok (when I use postman)

//form is required model​

router.route('/').post(function(req,res,next){
 res.send(req.body)
 form.create(
  {"first_name": req.body.first_name,
  "last_name": req.body.last_name
 })
  .then(function(data){ 
  res.send(data);
  console.log(data);
 }).catch(function(err){console.log(err)});
});

But I need to fire it form client side, not postman. And here i am lost. I can do it with but when i add onSubmit action it doesnt work. And I need to use new function to fire another thing without redirecting to another page. How to pass this.refs.first_name.value to body so that i could use fetch function?? Below react component

added this JavaScript/JSON snippet

export default class Form extends React.Component {
 constructor(props){
  super(props);
  this.handleSubmit = this.handleSubmit.bind(this);
 }
 handleSubmit(event){ 
  event.preventDefault();
  console.log(this.refs.first_name.value);
  fetch('/', {
   method: 'post',
   body: {
    "first_name": this.refs.first_name.value
   }
  });
 };
 render () {
  return (
   
   <div id="signup">
    <form onSubmit={this.handleSubmit}>
        <input ref="first_name" placeholder="First Name" type="text" name="first_name"/><br />
        <input placeholder="Last Name" type="text" name="last_name"/><br />
       <button type="Submit">Start</button>
    </form>
​
   </div>
​
  )
 }
}

Amir Hoseinian

I guess the way you are using ref has been deprecated. try below see if you have any luck.

export default class Form extends React.Component {
 constructor(props){
  super(props);
  this.handleSubmit = this.handleSubmit.bind(this);
 }

 handleSubmit(event){ 
  event.preventDefault();
  fetch('/', {
   method: 'post',
   headers: {'Content-Type':'application/json'},
   body: {
    "first_name": this.firstName.value
   }
  });
 };

 render () {
  return (
   
   <div id="signup">
    <form onSubmit={this.handleSubmit}>
        <input ref={(ref) => {this.firstName = ref}} placeholder="First Name" type="text" name="first_name"/><br />
        <input ref={(ref) => {this.lastName = ref}} placeholder="Last Name" type="text" name="last_name"/><br />
       <button type="Submit">Start</button>
    </form>
​
   </div>
​
  )
 }
}

Here is a link to react docs about refs

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

empty property and value in React fetch post request

React Native Post Request via Fetch throws Network Request Failed

React - PHP: How to fix problem of CORS with fetch request for POST request?

POST Request with Fetch API?

React - how to Redirect path after completing POST request using fetch

How to send a POST request to Flask API using Fetch in a React app

Django, react & fetch - submitting CSRF token on post request

How to send a fetch post request from react component to backend

How can I pass POST parameters in fetch request? - React Native

How to throw Catch in fetch POST request in react native

React Fetch Request

making POST request using fetch

Empty body in fetch post request

fetch API POST request response

React native fetch request failed

Problem with nested fetch request in React

Fetch cURL request using React

React + Axios double POST request to spring RestController (also in fetch, seem not to be OPTIONS)

React - fetch 'message' from Meta-Data element of the response from an Ajax post request

React Axios and Fetch POST method not working with C# WebAPI token request

Mocking fetch API for POST request using sinon, jest for react.js application

How to get Laravel CSRF-token for sending it through fetch post request in React?

React_Native Using Post Request with Fetch isn't work(PHP is work normaly)

In React, my POST fetch request works on the desktop but not on the iPad on Chrome, what's wrong?

Getting Null value in controller while making fetch post request from react

Issue with POST Request in React

Post request in react

Node Fetch Post Request using Graphql Query

POST request to JSONPlaceholder not taking effect in later fetch

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive