node.jsboxboxapiv2

Box API Node.js cant upload file 404 Error


I cant upload file with Box API my code:

var sdk = new BoxSDK({
  clientID: BOX_clientID,
  clientSecret: BOX_clientSecret
});





// Create a basic API client
var client = sdk.getBasicClient(BOX_accesstoken);



var fileData = fs.createReadStream('C:\\Exports\\test.txt')

client.files.uploadFile('123', 'test.txt', fileData, function(err, file) {
if (err){
console.log('err: ' + err);
}
else{
console.log('file uploaded: ' + file);  
}
});


// Get some of that sweet, sweet data!
client.users.get(client.CURRENT_USER_ID, null, function(err, currentUser) {
  if(err) throw err;
  console.log('Hello, ' + currentUser.name + '!');
});

This is the output

Hello, UserXYZ!
err: Error: Unexpected API Response [404 Not Found] (not_found: "Not Found")

Also I really don´t understand how to refresh my token with node.js the code from the docs is not working for me. Has somebody working sample codes for uploading files and how I can endless use a token I don´t want to enter new access codes everytime.


Solution

  • The first parameter to client.files.upload needs to be a valid folder_id so I believe that's why the [404 Not Found] appears. So you can try something like '0'.

    Here's an example using jwt and it will take care of the token refresh.

    // --------------- jwt --------------------------
    var BoxSDK = require('box-node-sdk');
    var fs = require('fs');
    var path = require('path');
    
    var CLIENT_ID = 'xxxx',
      CLIENT_SECRET = 'xxxx',
      PUBLIC_KEY_ID = 'xxxx',
      PRIVATE_KEY_PATH = 'xxxx',
      PRIVATE_KEY_PASSPHRASE = 'xxxx',
      ENTERPRISE_ID = 'xxxx';
    
    var sdk = new BoxSDK({
        clientID: CLIENT_ID,
        clientSecret: CLIENT_SECRET,
        appAuth: {
          keyID: PUBLIC_KEY_ID,
          privateKey: fs.readFileSync(path.resolve(__dirname, PRIVATE_KEY_PATH)),
          passphrase: PRIVATE_KEY_PASSPHRASE
        }
    });
    
    // --------------- your code ---------------------
    var client = sdk.getAppAuthClient('enterprise', ENTERPRISE_ID);
    
    var fileData = fs.createReadStream('C:\\Exports\\test.txt')
    client.files.uploadFile('0', 'test.txt', fileData, function(err, file) {
    if (err){console.log('err: ' + err);
    }
    else{console.log('file uploaded: ' + file);  
    }
    });
    
    
    // Get some of that sweet, sweet data!
    client.users.get(client.CURRENT_USER_ID, null, function(err, currentUser) {
      if(err) throw err;  console.log('Hello, ' + currentUser.name + '!');
    });