简体   繁体   中英

How do I use javascript require?

I have spent a day trying to figure this out. Given my js knowledge is dated I end up sorting out a moshpit of 'new' technologies where every doc and author expects you to know these things. It all creates one big brainfog. So I ask if anyone can explain how i enable require and Request in the code Im trying out.

To be specific, I have a working php API on my server using Hawk HTTP authentication. I am trying out the example javascript from the Github repo.

https://github.com/hueniverse/hawk

Client Code:

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)'));
});

Error

ReferenceError: require is not defined

I can relate to that this would cause an error when require is not part of plain javascript. What will i need to understand/learn/implement to make this work? Note that this is all on the client side.

The module you are looking at is designed to run under NodeJS (which has native support for require ) and not in a browser.

You might be able to get it to run in the browser , but it is likely that you cannot due to the same origin policy and should not because it would leak your credentials to anyone who visits your website.

require is part of the node API and is not available in the browser. In order to use modules in the browser, you will need to run your code through a bundler such as Webpack or Browserify first.

Be aware that there are still some modules (such as fs ) which cannot run in the browser due to the way they interact with the system (ie reading a file from disk). I believe request falls in that same category.

I recommend you use Browserify to start out, due to its simplicity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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