Node Express post json body with custom header


Node Express post json body with custom header

我想返回自定义标题,如"201, 'New Student created'",但我也有一个体返回{"id":1234,"name":john,"major":English}

app.post('/api/v1/students/', function (req, res) {
          ...
          obj = {
                  "id" : id, 
                  "name" : sname,
                  "major" : smajor,
          };
          ...
          ...
          res.status(201).json(obj);
          res.send('New Student created');
  });
使用v0.12.0

我相信标题和正文需要在json对象,但我不确定格式是什么

解析正文和报头

$resp=curl_exec($ch);                
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($resp, 0, $header_size);
$body = substr($resp, $header_size);

Express支持使用append向响应对象添加自定义标头。

app.post('/api/v1/students/', function (req, res) {
    // Create student code
    // Create the response
    res.append('Created', 'New Student Created');
    res.status(201).json(obj);
});

根据这些文档,你可以使用http_parse_headers打破你的$headers字符串成一个关联数组,你可以通过迭代访问你的头,通过你的响应。

根据Express文档,一种方法是使用set()方法来设置HTTP头。

res.set('New-Student-Created', 'true');
res.status(201).json(obj);