javascript - 如何从 Express 中的 router.post() 内的函数代码返回 promise 解析或拒绝?

标签 javascript node.js express promise

下面是我在express(node.js)中的代码

router.post('/example.json', function (req, res) {

  // getFileInfo is a function to return a array
  return getFileInfo(req.body.fileList).then((array) => {

  axios({
    method: 'post',
    url: 'http://localhost:5000/sendTestImage.json',
    data: {
      file: array
    }
  }).then((res) => {
    return Promise.resolve();
  }).catch((err) => {
    return Promise.reject();
  })
});

完成 axios 调用后如何返回 Promise 解析或拒绝并将其返回给调用“/example.json”的客户端?

最佳答案

您不应该返回任何内容,如果调用成功,只需将数据发送到客户端即可。如果出现错误,请设置正确的http响应状态并发送错误:

router.post('/example.json', function (req, res) {
  getFileInfo(req.body.fileList)
    .then(array => {
      return axios({
        method: 'post',
        url: 'http://localhost:5000/sendTestImage.json',
        data: {
          file: array
        }
    })
    .then(data => res.send(data))
    .catch(err => res.status(400).send(err));
});

关于javascript - 如何从 Express 中的 router.post() 内的函数代码返回 promise 解析或拒绝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45489839/

相关文章:

javascript - 使用 Angularjs 和 UI Router 的 event.preventDefault() 删除浏览器历史记录

node.js - 在 Express 中签署 Cookie

node.js - Angular 未定义

node.js - 如何使用node.js和express在前端打印console.log

javascript - 动态加载 JavaScript

javascript - ExtJS ComboBox triggerAction : "all" really do? 是什么意思

javascript - 联系表格 7 验证标签表格 css

javascript - 使用express.js 打破程序流程

javascript - Nodejs POST 请求的异步问题

express - 如何将Google Cloud Storage与react.js结合使用?