简体   繁体   English

如何在Reactjs中向Node.js RESTful API发出POST请求

[英]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. 我有使用nodejsexpress构建的后端nodejs API,也有基于Reactjs构建的前端,我试图创建一个登录页面。 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. 我的想法是在ReactjsNodejs API发出POST请求,包括用户名和密码,然后后端将检查请求信息是否正确将返回令牌,否则将返回失败消息。 But I don't know which is the proper way to make a POST request in reactjs . 但是我不知道哪种是在reactjs发出POST请求的正确方法。 Do i just using $.ajax() ? 我是否只使用$.ajax() I am trying to avoid using jquery because I think there are many ways to do the same stuff. 我试图避免使用jquery因为我认为有很多方法可以做同样的事情。 Thanks in advance. 提前致谢。

You can use fetch if you don't want to go for third party libraries. 如果您不想使用第三方库,则可以使用fetch

Check here a nice article about how to use fetch in react. 在这里查看有关如何在react中使用fetch的不错的文章。

Use axios . 使用axios There's no need to use jquery . 无需使用jquery

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

options will be: { username: username, password: password ...etc } 选项将是: { 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 . 我对fetch喜欢是,您可以定义一个baseurl (而不是为每个AJAX请求axioshttp://localhost:5000/api/... ),而axios自动处理JSON

you should use axios.js with saga.js frameworks. 您应该将axios.js与saga.js框架一起使用。

 // 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);
      });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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