[英]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. 我有使用
nodejs
和express
构建的后端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. 我的想法是在
Reactjs
向Nodejs
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. 提前致谢。
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
请求axios
写http://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.