Node JS: ReferenceError: require is not defined - javascript

I want to use MySQL database. I installed MySQL with command npm i mysql. In order to use it, I wrote:
var mysql = require('mysql');
But when I run the program, it shows ReferenceError: require is not defined error.
I wrote this line in home.ejs file within a script tag.

Home.ejs isn't the approriate file to write this line in.
ejs files won't contains that much logic (except condition and loop over some element in your dom).
Basically what you want to do is anodeJs script file which will connect to mysql, handle the request and serve your ejs files with your data.
Using express you'll have something like this in your node file :
app.get("/home",(req,res)=>{ res.render("home.ejs", {data : data}) (where data is what you get from your DB

By default require() is not a valid function in client side javascript. I recommend you look into require.js as this does extend the client side to provide you with that function.

you need to do your mysql processing before you get to the ejs template. Right now, you are trying to use require in a template, which is being rendered on the browser. You won't be able to do that without using a module loader like requirejs.

require() by default is a NodeJS function on the server side. You can use require.js like Abhilash said. It's bad practice to have mysql in the browser. Your username, password, and host will be exposed to the world.

The browser does not have an API that require modules. Also, this is something that you would do in a nodejs application (in the backend NOT the front end), typically in a .js file.

Related

How to use nodejs file with html file?

I have a frontend in HTML and JAVASCRIPT. I need to get value from nodejs file and display it in HTML label. So I create new node js file node.js as:
const Web3 = require('web3');
const web3 = new Web3('https://kovan.infura.io');
web3.eth.getBalance('0x9E632F36D8193a23ee76e7C14698aCF4b92869A2').then(console.log);
I include this file in script tag as:
<script src="node.js"></script>
First I want to look output in the console but it is giving an error
Uncaught ReferenceError: require is not defined
So, I try this code directly in HTML file within the script tag without including node file but still gives the same error.
Can somebody help me with this? I am new to use all this together.
Somehow, I managed to find a solution. I used browserify, which makes easy for me to run the nodejs code from my web app.
Browsers don't have the require method defined, but Node.js does. With Browserify you can write code that uses require in the same way that you would use it in Node.
browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single tag.
I referred this link: http://browserify.org/

Node require mongo error - 'require is not defined'

I'm having a problem with mongo and node. I have a file called db.js where I put the require('mongodb') and if I import it to my index.html, I got the error:
require is not defined
But if I go to the db.js file and use 'node db', it works. I've tried import, require, src but still nothing works. Someone could help me?
<script type="text/javascript">
import 'js/db.js';
const MongoClient = require('mongodb');
Is there a reason that you need to configure mongodb on the front end? Unless you have a really good reason, I would strongly recommend against that. You basically throw any notion of security right out the window by doing that.
Now that we've got that cleared up, I think what you really are asking, is how you can let users make requests to mongodb from the front end. For that, you should use fetch or an HTTP request/response library like Axios in your front end javascript. Use either of these to send requests to your node backend and then you can interact with mongodb by passing along the user-submitted data from there.
Let me know if that helps you at all or if you need more help.
You should require mongodb statement on server side code not on the browser side.Browser don't understand the require/import statement.
You can try using module like browserify to see such functionality if it works.
http://browserify.org/

Django views to run python script

I have chatbot web application in Django framework. So far everything is working, but now, I want to run the chatbot python script using ajax and calling the view for it from the Javascript file. I have an API using REST and the view for the python script and the ajax to call that view.
view.py:
from chat.chatbot1 import main_chatbot
def run_python_script(request):
os.system('python3 main_chatbot.py')
return HttpResponse("OK")
index.js:
function run_chatbot_script(){
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:8000/chatbot/run_python_script/',});
and the python script folder is located in the chat app inside the chatbot django project.
The problem is that the view can't find the file and this error appears:
python3: can't open file 'main_chatbot.py': [Errno 2] No such file or directory
If is in the same folder you should import it:
Example if is the same folder as the view.py
import .run_python_script
Then just call the functions you want...
You can also put the full path in the os.system but it doesnt seem alright...
Your Django application will probably have the working directory as the location your manage.py file, so it will expect the python script in the same directory.
Use the full path to the script, or the path relative to the directory where mange.py is.
so maybe something like :
os.system('python3 chat/main_chatbot.py')
or
os.system('python3 /home/user/django_project/chat/main_chatbot.py')
(The answer suggesting importing the script is probably a better way of doing it unless there is a specific need to run it as a separate process).
You ought to give the full path of main_chatbot.py.
The best way to do that, could be using pkg_resources.resource_filename, like this:
import pkg_resources
script_path = pkg_resources.resource_filename('chat', 'main_chatbot.py")
Where chat is the name of the package which contains your script.
To run the script, it could be a good idea to use the same Python executable as your Project's executable (your virtualenv).
Do do that, you can use sys.executable to get the Python path used by your virtualenv:
import sys
python_path = sys.executable
It is a best practice to replace os.system by subprocess.check_call, like this:
import subprocess
subprocess.check_call([python_path, script_path]
See Replacing Older Functions with the subprocess Module

Node.js Error: require is not defined in clientside js file

I have a Javascript file in which I have data that needs to be saved into a Mongoose schema and subsequently inserted into a MongoDB table. The schema is defined in a file in a separate directory so I tried to essentially import it by including the following line at the top of the file:
//import schema for sketches
var SketchSchema = require('../schemas/sketch_objs');
I then got the error "Uncaught ReferenceError: require is not defined"
which I found out here was due to the fact that require() doesn't exist on the client-side. As suggested in the answer for that post, I installed Browserify in order to be able to require the schema javascript file.
I couldn't really ascertain the specific usage of Browserify's functionality to achieve this but it seemed from the github readme that something like the following has to be done:
$ browserify main.js > bundle.js
where the required files in main.js will be included inside of bundles.js. I tried to doing this for the file that needed to include the schema and successfully generated the new file; however, for some reason when I run the project, I still get the error about require not being defined. Is it supposed to be that the new file generated by Browserify is supposed to be used instead of the old file? If this isn't the case, what is the correct way to require another js file inside a file on the client side?
So
you need browserify to require the JS file CommonJs way.
I do not think mongoDB is compatible with browserify, FYI, https://jira.mongodb.org/browse/NODE-698

I need a strongloop example wrote in javascript without angular

I want to have a strongloop example only using javascript without angular.
There's no complete working example without angular for now.
I want to simply include the browser.bundle.js in my index.html, then sync data from/to server side. In fact, I'm trying to replace pouchdb in my program since the couchdb seems not success in open source community.
I can't follow up this document correctly:
Running Loopback in the browser
create browser-app.js with the content from Running Loopback in the browser
copy past the content to browser-app.js
npm install loopback loopback-boot
browserify browser-app.js -o app.bundle.js Then I got error: Error: Cannot find module 'loopback-boot#instructions' from '/Users/simba/Projects/traveller-app/client/node_modules/loopback-boot'
There are few steps for this but its pretty simple.
Bootstrap your application via slc loopback.
Delete server/boot/root.js.
Uncomment two lines in server/server.js, it should look like:
...
// -- Mount static files here--
// All static middleware should be registered at the end, as all requests
// passing the static middleware are hitting the file system
// Example:
var path = require('path'); //this line is now uncommented
app.use(loopback.static(path.resolve(__dirname, '../client'))); //this line is now uncommented
...
Create index.html in the client dir (ie. client/index.html) with your contents.
That should get you a basic set up with just a basic front-end working. Let me know if you have any more issues.

Categories