【问题标题】:res.send is not returning the expected data: JavaScript, Express, Node?res.send 没有返回预期的数据:JavaScript、Express、Node?
【发布时间】:2019-09-09 22:16:36
【问题描述】:

我有一个提交患者姓名的帖子请求,服务器应该回复我patient_id 作为响应。我收到了 200 条回复给客户,但是我没有收到我需要的 patient_id 回复。当我在服务器上进行控制台登录时,我可以看到 patient.id 已生成并且也没有错误。想知道我是否缺少什么?

Response - 
body: (...), bodyUsed: false, headers: Headers {}, ok: true, redirected: false, status: 200, statusText: "OK", type: "basic", url: "http://localhost:4000/patient/add"
//client side post 

 handleSubmit(e) {
        e.preventDefault();
        const postUrl = '/patient/add';
        fetch(postUrl, {
            method: 'POST',
            headers: {'Content-Type': 'text/plain'},
            body: this.state.patientName
        })
            .then(response=> {
                if (!response.ok) console.log('failed', response);
                else console.log(response);
            });
    }
  this.app.post('/patient/add', bodyParser.text(),
            this.route_post_patient_add.bind(this));
 async route_post_patient_add(req, res) {
        /** @type {string} */
        const body = req.body;

        if (body === undefined) {
            logger.warning('Set room patient failed, body missing');
            res.sendStatus(400);
            return;
        }

        if (body === "") {
            logger.warning(' body is empty');
            res.sendStatus(400);
            return;
        }

        try { 
            const patient_id = await this.save_patient(body);

            res.send(patient_id);
            console.log(patient_id); //logs the id that is generated

        }
        catch (err) {
            logger.error('Set patient failed, internal error', { err });
            res.sendStatus(500);
        }
    }

【问题讨论】:

  • 在您的浏览器“网络”开发者工具中实际的响应正文是什么样的?

标签: javascript node.js api express server


【解决方案1】:

fetch 中的 response 对象不是原始主体。

你必须调用一个函数并解决一个promise来获取数据。

例如:

fetch("foo")
    .then(parse_body)
    .then(log_data);

function parse_body(response) {
    return response.text();
}

function log_data(response_text) {
    console.log(response_text);
}

延伸阅读:MDN: Using Fetch

【讨论】:

  • 不知道我是怎么错过的,因为我每天都使用它哇。我从来没有用过response.text() 我猜这对简单的字符串有用吗?
  • response_text 参数是如何工作的。什么被通过了?我还需要能够将 id 保存在 var 中,并且在 handleSubmit @Quentin 上可用
  • @Jereme — 解析 response.text() 方法返回的承诺的结果。
猜你喜欢
  • 1970-01-01
  • 2023-02-23
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 2016-05-05
  • 2017-03-29
  • 2018-01-31
  • 1970-01-01
相关资源
最近更新 更多