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/
Related
I`m only starting my JS journey and I will be really grateful if you help me to receive data using the JS. I found that info on the alcor exchange site that is the exchange site for wax (gaming crypto currency).
What is on site:
// Code not tested yet, and provided for explanation reason
import fetch from 'node-fetch'
import { Api, JsonRpc, RpcError } from 'eosjs'
const rpc = new JsonRpc('https://wax.greymass.com', { fetch })
// Get buy orderbook from table
const { rows } = await rpc.get_table_rows({
code: 'alcordexmain',
table: 'buyorder',
limit: 1000,
scope: 29, // Market id from /api/markets
key_type: 'i128', // we are using it for getting order sorted by price.
index_position: 2
})
I faced with some trouble because of JSHint version and updated it to 9. But still "await" is red and JSHint is asking for semicolon after it - which causes huge amount of new errors. However the project is opening in the browser with no info of course. But in the console I see an error.
index.html:1 Uncaught TypeError: Failed to resolve module specifier "node-fetch". Relative references must start with either "/", "./", or "../".
P.S. I checked the posts with such error but actually didn't understand what should I do because all of them are proposing some changes for JSON file and I only have index.html and that js. file.
There is a difference between JavaScript in your browser and JavaScript on a server.
JavaScript in a browser is the code that can be injected into HTML (inlined or linked), which is evaluated by the browser.
JavaScript on a server is not related to JavaScript in a browser. The language is the same, but the environment is not. It's like “draw in Paint” and “draw on a real life canvas”. Colors are the same, but everything else is not.
So, what you are trying to do here is to run server-side JavaScript in a browser. That's the real reason you're getting this error.
There are two ways to fix this error.
Probably the one you should go
You should install Node.js, read about npm, init your npm project, put everything into .js file and eval using Node.
In a nutshell, let's say you've already installed Node.js and node -v outputs something in your terminal. Then everything you need to do is:
$ cd path/to/the/directory/you/like
$ npm init -f
$ npm install --save node-fetch eosjs
$ touch index.js
Then edit index.js using your favorite editor, adding there the code you're trying to run.
You may encounter error due to using await on a “top-level”. In this case, put it into an async function:
import fetch from 'node-fetch'
import { Api, JsonRpc, RpcError } from 'eosjs'
const rpc = new JsonRpc('https://wax.greymass.com', { fetch })
(async () => {
const { rows } = await rpc.get_table_rows({
code: 'alcordexmain',
table: 'buyorder',
limit: 1000,
scope: 29, // Market id from /api/markets
key_type: 'i128', // we are using it for getting order sorted by price.
index_position: 2
});
})();
Aaaand, that's it. You do not need to run browser here at all.
Probably the one you should not go, but can
If you need to run your JavaScript in a browser, then you need to either bundle all the deps using a tool like webpack (which still requires you to use Node.js & npm), or you may replace the deps you're trying to use with client-side alternatives.
E.g. instead of requiring node-fetch you may use Fetch API.
What to use instead of eosjs I do not know, but if you decide to use this dependency in a browser, you will at least need to use import maps to tell the browser how to resolve such dependencies. Because, well, the error you've got tells you exactly this: your browser does not know what you're trying to import. Browsers use URLs as import paths, not ids (or “bare names”).
Alright, I've about reached the end of my sanity on this one.
So, I have a basic React frontend w/ an Express backend. React is running off of localhost:3000, the backend is running off of localhost:3030. Following along on a guide for setting up some Spotify integration, everything works fine up until I hit the portion on setting up a proxy. (I have a slightly different setup from the Spotify guide, all my stuff runs through /spotify/auth rather than /auth)
I installed http-proxy-middleware, created the setupProxy.js in my /src folder, and if I ever try to load up localhost:3000 as normal, I get nothing-- my app doesn't load at all.
The only way to have the app appear again is to remove the file. The one on the spotify guide is a bit out of date as far as I can tell anyway, but even using suggestions found elsewhere, I've gotten no luck. Here is the current setup I have for my setupProxy.js file:
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
"/spotify/**",
createProxyMiddleware({
target: "http://localhost:3030",
changeOrigin: true,
})
);
};
I've even removed the actual fetch that would be making use of the proxy and still have no luck loading my page. I am also unable to use "proxy": "http://localhost:3030" in my package.json as it throws:
Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
- options.allowedHosts[0] should be a non-empty string."
Managed to solve my problem, though I am still unsure of why it works.
The issue I was running into stems from using "type": "module" in the package.json. I was using correct import statements in all of my backend, as well as tried to use it for the setupProxy.js as well, however this would always result in the issue from the question. After removing the line and swapping out the imports for requires in my backend, everything started working.
It seems like a strange compatibility issue, but there's probably a much better explanation.
Had the same problem as you where my react app wasn't loading because of http-proxy-middleware. Different problem/solution, but for people that also had this problem, and were following this youtube video https://www.youtube.com/watch?v=hxyp_LkKDdk
The tutorial has
const proxy = require("http-proxy-middleware")
instead of
const {createProxyMiddleware} = require("http-proxy-middleware")
After I made that change, my issue was solved. Don't forget to change "proxy" to "createProxyMiddleware" in app.use() as well
I've adopted a project with Handlebars and have run into an issue getting handlebars to render templates client side.
Basically the way it's setup at the moment is the templates are rendering out server side. I'm at a stage now where I need to be able to call handlebars in AJAX responses to reference handlebars templates using the following method:
<script id="ajax-comment" type="text/x-handlebars-template">
<li>
<p>{{{comment}}}</p>
</li>
</script>
I understand how the method works but where i'm having trouble is actually getting the handlebars function to work on the client side in one of my javascript modules. Here is what i'm trying:
var Handlebars = require('handlebars');
console.log(Handlebars);
The error i'm getting whenever I try this is:
Error: Can't resolve 'fs' in ...\node_modules\handlebars\lib'
FS is obviously not available client side hence why it's not working but after reading through the various documentation on Handlebars around this, it seems to be the way you should do it. I'm not entirely sure why i'm getting this error, i'm not sure if this could be an issue with webpack. Handlebars is being called in via gulp-hb so not sure if this could also be the issue.
Any help as to why this could be happening would be much appreciated! Happy to provide any config files that could also help debug this.
An example
function onInitFs(fs) {
console.log('Opened file system: ' + fs.name);
}
window.requestFileSystem(window.TEMPORARY, 5*1024*1024 /*5MB*/, onInitFs, errorHandler);
You can try this using html5 fs api
https://www.html5rocks.com/en/tutorials/file/filesystem/
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.
I'm trying to use the resemblejs library (http://huddle.github.io/Resemble.js/) to compare two images. However, when I have created a directory and added resemblejs as a dependency, but when I try to run the following:
nodejs test.js, I get the following error
var api = resemble(fileData).onComplete(function(data){
^
ReferenceError: resemble is not defined
I've never used NodeJS before, so it might be something really simple. Any ideas?
You can't get directly node module instance from it. You can check this issue on its repo. node-resemble is an Node port of Resemble.js.
Hope it will be useful for you.