Require is not defined nodejs

筅森魡賤 提交于 2021-01-02 08:14:39

问题


Trying to use this smartsheet api: http://smartsheet-platform.github.io/api-docs/?javascript#node.js-sample-code

and its telling me to do this for nodejs:

var client = require('smartsheet');
var smartsheet = client.createClient({accessToken:'ACCESSTOKEN'});

So i do this in my main.js file but I get the error: Uncaught ReferenceError: require is not defined

I think its because im new to nodejs/npm but I cannot find it anywhere where to actually put this require function. I think i need to mess with my node.js file but im note entirely sure. Any link to documentation or suggestions are greatly appreciated!


回答1:


This is because you are using node-specific calls in the browser! NodeJS is a server-side technology and not a browser technology. Thus, node-specific calls will only work in the server.

The smartsheet api you're trying to use needs to be called from the server-side code and not client side code.

For your case, you can set up ExpressJS and create an dummy api which internally calls the smartsheet api.

If you indeed want to use such calls on the client side, you can use CommonJS client side-implementations




回答2:


Try Removing "type": "module", from package.json




回答3:


Replace all require statements to import statements. Example:

//BEFORE:
var client = require('smartsheet');
//AFTER:
import client from 'smartsheet';

Worked for me.




回答4:


require() is a function provided in NodeJS and it wont work on client/browser because there is nothing like require() on client side




回答5:


require() does not exist in the browser/client-side JavaScript

More info on Client on node: Uncaught ReferenceError: require is not defined




回答6:


you can't use require directly in browser. you need RequireJS, a JavaScript module loader.

This is introductory note from RequireJS.

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.



来源:https://stackoverflow.com/questions/38343751/require-is-not-defined-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!