[英]How do I use javascript require?
我花了一天的时间试图弄清楚这一点。 鉴于我的js知识已经过时,我最终整理出了一些“新”技术,每个文档和作者都希望您了解这些知识。 这一切都造就了一大群人。 所以我问是否有人可以解释我如何在代码中尝试启用require和Request。
具体来说,我在服务器上使用Hawk HTTP身份验证的PHP API正常工作。 我正在从Github存储库中尝试示例javascript。
https://github.com/hueniverse/hawk
客户代码:
const Request = require('request');
const Hawk = require('hawk');
// Client credentials
const credentials = {
id: 'dh37fgj492je',
key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
algorithm: 'sha256'
}
// Request options
const requestOptions = {
uri: 'http://example.com:8000/resource/1?b=1&a=2',
method: 'GET',
headers: {}
};
// Generate Authorization request header
const header = Hawk.client.header('http://example.com:8000/resource/1?b=1&a=2', 'GET', { credentials: credentials, ext: 'some-app-data' });
requestOptions.headers.Authorization = header.field;
// Send authenticated request
Request(requestOptions, function (error, response, body) {
// Authenticate the server's response
const isValid = Hawk.client.authenticate(response, credentials, header.artifacts, { payload: body });
// Output results
console.log(`${response.statusCode}: ${body}` + (isValid ? ' (valid)' : ' (invalid)'));
});
错误
ReferenceError:需求未定义
我可以认为,当require不是普通javascript的一部分时,这将导致错误。 我需要了解/学习/实施什么才能完成这项工作? 请注意,这些全部在客户端上。
require
是节点API的一部分,在浏览器中不可用。 为了在浏览器中使用模块,您需要首先通过捆绑程序(例如Webpack或Browserify)运行代码。
请注意,由于它们与系统交互的方式(即从磁盘读取文件),仍有一些模块(例如fs
)无法在浏览器中运行。 我认为request
属于同一类别。
由于其简单性,我建议您使用Browserify入门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.