繁体   English   中英

Express中的JSON.stringify api响应

[英]JSON.stringify api response in express

我正在阅读一些代码,我看到了

router.post('/', (req, res) => {
  const {author, message} = req.body;

  if (author === undefined) {
    res.status(400);
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ message: 'Every message requires an author' }));
    return
  }

  res.redirect('/');

});

我不知道为什么它需要使用JSON.stringify,我不能只做res.send({ message: 'Every message requires an author' })吗?

并且该路由具有单元测试,它使用了JSON.parse

describe('when the author is blank', () => {
      it('renders an error message', async () => {
        const message = 'Server Testing';

        const response = await request(app)
          .post('/messages')
          .send({message});

        assert.equal(response.status, 400);
        assert.equal(JSON.parse(response.text).message, 'Every message requires an author')
        });
    });

我看不到使用JSON.stringify和JSON.parse的意义,请给我启发。

您可以删除,但是即使您传递的是json,有时也会导致一些意外结果。 我将与您分享一个例子。 我正在一个项目中,我需要以json格式发送酒店ID。我正在发送确切的格式,但是服务器不接受该格式,并抛出500错误,因此始终保持安全状态并声明您的数据总是更好在一个单独的变量中,然后在``get / post''请求中使用json.stringify格式传递该数据。 所以拥有那些总是很不错的:-)

服务器端使用:

res.json({a: 123})

代替

res.send(JSON.stringify({a: 123}))

http://expressjs.com/en/api.html#req.body

然后在单元测试中:

const response = await request(app).post('/messages').send({message});

const data = await response.json();

暂无
暂无

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

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