简体   繁体   English

节点/表达如何在req.header上拆分

[英]Node/express how to .split on req.headers

I am trying to check if an item exists in a req.headers I have here to decide what to send back to the user. 我正在尝试检查req.header中是否存在某个项目,我在这里决定要发回给用户的内容。 So I have this - 所以我有这个-

function serveAppData(req, res) {
console.log("CHECKME", req.headers);
//var headerSSo = req.headers).... .split("#canSend")
//if (headerSSo)
var data = require('../static/app-data.json');
res.status(200).json(data);
}

The log works fine - however I am wondering how I can wrap a conditional around this data so I can check if the '#canSend' string is inside that header object and use it as a conditional. 日志工作正常-但是我想知道如何围绕该数据包装一个条件,以便可以检查'#canSend'字符串是否在该标头对象内并将其用作条件。 Do I have to turn it to json or something first to check it? 我是否必须先将其转换为json或其他内容进行检查?

I tried flat out doing 我尽力了

  req.headers.split("#canSend");

So doing this gives me "TypeError: Illegal invocation" in the dev console and , "TypeError: undefined is not a function" in the shell. 因此,这样做在开发人员控制台中给了我“ TypeError:Illegal invocation”,在外壳程序中给了我“ TypeError:undefined is a function”。

Which caused some errors so I think I'm missing a step here to do this correctly. 这引起了一些错误,所以我想这里缺少正确执行此操作的步骤。 My desired result is to check if a string is in the key of 'user-tokens' in side that header object. 我想要的结果是检查字符串是否在该标头对象的'user-tokens'键中。 Maybe I have to approach this different entirely? 也许我必须完全采用这种不同的方法? Would much appreciate any input. 非常感谢任何投入。 Thanks! 谢谢!

req.headers in express is a key-value JavaScript object where key are name of header, and value is value. req.headersexpress是一个键-值JavaScript对象,其中关键是报头的名称,值是值。 So to check if item exist, you can use native method: 因此,要检查项目是否存在,可以使用本机方法:

req.header.hasOwnProperty('#canSend');

If #canSend is value of HTTP Header, than you need to iterate and find it like this: 如果#canSend是HTTP标头的值,则需要进行迭代并找到它,如下所示:

for( var prop in req.header ) {
    if( req.header.hasOwnProperty( prop ) ) {
         if( req.header[ prop ] === '#canSend' )
             return true;
    }
}

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

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