简体   繁体   中英

How to make a POST request to a nodejs RESTful API in reactjs

I had my backend restful API built with nodejs and express , I also have a front-end built on Reactjs, I am trying to make a login page. My idea is making a POST request in Reactjs to my Nodejs restful API, including username and password, then the back end will check if the request information correct will return a token, else will return a fail message. But I don't know which is the proper way to make a POST request in reactjs . Do i just using $.ajax() ? I am trying to avoid using jquery because I think there are many ways to do the same stuff. Thanks in advance.

You can use fetch if you don't want to go for third party libraries.

Check here a nice article about how to use fetch in react.

Use axios . There's no need to use jquery .

axios.post("http://api/login", { options }).then(res => ...).catch(err => ...)

options will be: { username: username, password: password ...etc }

What I like about it over fetch is that you can define a baseurl (instead of writing http://localhost:5000/api/... over and over for each AJAX request) and axios automatically handles JSON .

you should use axios.js with saga.js frameworks.

 // Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); 

Simply achieve this

function submitRequest(opts) {
      console.log('Posting request to your API...');
      fetch('http://your_url', {
        method: 'post',
        body: JSON.stringify(opts)
      }).then(function(response) {
        return response.json();
      }).then(function(data) {
       console.log(':', data);
      });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM