我花了一天时间试图解决这个问题。鉴于我的 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 is not defined
我可以理解,当 require 不是普通 javascript 的一部分时,这会导致错误。我需要理解/学习/实现什么才能使这项工作成功?请注意,这一切都在客户端。
最佳答案
您正在查看的模块设计为在 NodeJS 下运行(它具有对 require
的 native 支持),而不是在浏览器中。
您也许能够将其到达run in the browser ,但由于same origin policy,您可能不能 并且不应该,因为它会将您的凭据泄露给访问您网站的任何人。
关于javascript - 如何使用 javascript require?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43468826/