简体   繁体   English

Express中的JSON.stringify api响应

[英]JSON.stringify api response in express

I'm reading some codes and I saw this 我正在阅读一些代码,我看到了

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('/');

});

I've no clue why it need to use JSON.stringify, can't I just do res.send({ message: 'Every message requires an author' }) ? 我不知道为什么它需要使用JSON.stringify,我不能只做res.send({ message: 'Every message requires an author' })吗?

And the route has an unit test, it used JSON.parse 并且该路由具有单元测试,它使用了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')
        });
    });

I don't see the point of using JSON.stringify and JSON.parse, please enlighten me. 我看不到使用JSON.stringify和JSON.parse的意义,请给我启发。

You can remove but it may lead to some unexpected results at times even if you are passing exact json. 您可以删除,但是即使您传递的是json,有时也会导致一些意外结果。 I will share an example with you. 我将与您分享一个例子。 I was working on a project where in I need to send a hotel id in json format .I was sending the exact format but server was not accepting that and was throwing 500 error so it's always better to stay on a safer side and declare your data in a separate variable and pass in that data using json.stringify format in the get/post request.It comes good practices. 我正在一个项目中,我需要以json格式发送酒店ID。我正在发送确切的格式,但是服务器不接受该格式,并抛出500错误,因此始终保持安全状态并声明您的数据总是更好在一个单独的变量中,然后在``get / post''请求中使用json.stringify格式传递该数据。 So it's always good to have those :-) 所以拥有那些总是很不错的:-)

Server side use: 服务器端使用:

res.json({a: 123})

instead of 代替

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

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

Then in the unit test: 然后在单元测试中:

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