Node Express发布带有自定义标头的json主体

时间:2015-10-22 20:27:50

标签: php node.js express

我想返回一个自定义标题,例如"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 obj中,但我不确定格式是什么

解析正文和标题

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

2 个答案:

答案 0 :(得分:1)

Express支持使用response objectappend添加自定义标头。

if((add).equals(command[0]))

根据这些文档,您可以使用http_parse_headersapp.post('/api/v1/students/', function (req, res) { // Create student code // Create the response res.append('Created', 'New Student Created'); res.status(201).json(obj); }); 字符串分解为一个关联数组,您可以迭代该数组以访问通过您的回复传递的标题。

答案 1 :(得分:1)

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

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