Node.js中Express框架怎么使用axios同步请求

前端开发   发布日期:2025年01月13日   浏览次数:274

这篇文章主要介绍了Node.js中Express框架怎么使用axios同步请求的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Node.js中Express框架怎么使用axios同步请求文章都会有所收获,下面我们一起来看看吧。

首先定义一个方法syncAxios

  1. let axios = require('axios');
  2. exports.syncAxios = function (obj = {}) {
  3. let url = "http://www.rrbay.com/api/";
  4. return new Promise((resolve, reject) => {
  5. axios(url, {
  6. method: 'POST',
  7. timeout: 5000,
  8. params: {
  9. sProcName: obj.sProcName,
  10. idNo: obj.id,
  11. userName: obj.qq,
  12. overTime: obj.endTime
  13. }
  14. }).then((res) => {
  15. resolve(res.data);
  16. }).catch((error) => {
  17. reject(error)
  18. })
  19. })
  20. };

然后在controllers 调用

  1. exports.check = function (req, res) {
  2. //定义async方法体
  3. XXXMode.findById(id).populate('author').exec(async function (err, result) {
  4. let dataCode = false;
  5. if(result.status ==0){
  6. //同步调用
  7. await baseapi.syncAxios({
  8. sProcName: 'Update',
  9. id: '000000-1111-2222-3333-9999999',
  10. qq: '391502069',//result.author.name,
  11. endTime: '2022/12/31 11:39:05'//result.EndTime
  12. }).then((data) => {
  13. console.log(data, 'res');
  14. }).catch((err) => {
  15. console.log(err && err.stack);
  16. });
  17. }
  18. result.save(function (err, onewxtob) {
  19. if (req.xhr) {
  20. return res.json({
  21. status: !err
  22. })
  23. }
  24. });
  25. });
  26. };

view中使用模板引擎jade,需要在请求

  1. check
后,延迟刷新页面显示请求结果
  1. setTimeout(function () {
  2. $(location).attr('href',window.location.href)
  3. }, 1000)

这里的setTimeout实现了延迟加载刷新页面的效果,结合控制器的交互,最终实现了同步操作的效果。

以上就是Node.js中Express框架怎么使用axios同步请求的详细内容,更多关于Node.js中Express框架怎么使用axios同步请求的资料请关注九品源码其它相关文章!