We are doing a web using HTML and JavaScript. We have some problems when trying to do the authorization process to connect to the Spotify API.
var express = require('express'); // Express web server framework
var request = require('request'); // "Request" library
var querystring = require('querystring');
var cookieParser = require('cookie-parser')
This code we found on the internet uses require() to get some data but Chrome says:
Reference error: require is not defined.
We found that the JavaScript node may be the problem so we installed npm and Browserify but is not working.
We also used this in our HTML:
<script type="text/javascript" src="node.js"></script>
<script type="text/javascript" src="js/main.js"></script>
HELP??
What you have is the code that suppose to run on the server side. Node, Express, are server side components, and you can't run them on the clients side (inside of the browser). Server side is using 'require' to manage and load modules, that is why you have require there.
I think what should you do is to send your request to the server and server should process authentication code that you have there and send response back with the status if user authenticated or not.
require() is not an existing method for client-side JS.
Use a <script> tag then call the method after it.
This was already answered here:
Client on node: Uncaught ReferenceError: require is not defined\
Node.JS is a serverside application and you are attempting to run this clientside.
Please try using and referring to this http://requirejs.org/
Related
Here is my HTML code in index.html.
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="stuff()">Click</button>
<script>
async function stuff() {
await connectToServer();
}
async function connectToServer() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
alert(this.responseText);
};
xhttp.open('GET', 'C:/Users/myName/myFolder/index.js', true);
xhttp.send();
return;
}
</script>
</body>
</html>
Then, here is my backend code in index.js.
const express = require('express');
const axios = require('axios');
const port = process.env.PORT || 8080;
const app = express();
app.get('/', (req, res) => {
res.sendFile('C:/Users/myName/myFolder/views/index.html');
});
app.listen(port, () => console.log(`Listening on port ${port}`));
I can type node index.js on the command line and run this program and go to http://localhost:8080/ . When I do this, the html page shows up as intended. However, when I click the button in order to make a GET request to the server side, I get a console error saying Not allowed to load local resource: file:///C:/Users/myName/myFolder/index.js . I'm using Google Chrome by the way.
I know that it is a security thing, and that you are supposed to make requests to files that are on a web server (they begin with http or https). I suppose then, my question is:
How do I make it so that my server file index.js can be viewed as being on a server so that I can call functions on the backend from my frontend?
You have to make an HTTP request to a URL provided by the server.
The only URL your server provides is http://localhost:8080/ (because you are running an HTTP server on localhost, have configured it to run on port 8080, and have app.get('/', ...) providing the only path.
If you want to support other URLs, then register them in a similar way and write a route to handle them.
The express documentation will probably be useful.
You should not need to load your server-side code into the browser. It's server-side code. It runs on the server. It isn't client-side code. It doesn't run in the browser. The browser does not need access to it.
If you want to load some actual client-side JS from the server, then use <script src="url/to/js"></script> (and not Ajax) and configure express' static middleware.
Let's improve your current flow by separating your backend API process from frontend hosting process. While backend can, it's not good in serving static html files (especially for local development purposes).
Run your backend as usual, node index.js. But as soon as this command will become more complicated, you will probably want to use npm scripts and do just npm start)
Run separate server process for frontend. Check out parcel, snowpack, DevServer. It can be as easy as npx parcel index.html, but this command is likely to change frequently with your understanding of your tool features.
To call backend, just add an API endpoint to an express app (just like you already did for serving static content), and call it, using backend process URL.
Usually, you will see your app on http://localhost/ and it should do requests to http://localhost:8080/.
If for some strange reason you will want to dynamically download js file from your server to execute it, you just need to serve this file from your frontend hosting process. In order to do so, different development servers have different techniques, but usually you just specify file extensions and paths you want to be available.
After editing frontend files, you will see hot-reload in browser. You can achieve the same for node process with various tools (start googling from nodemon)
If you find this way of operating not ideal, try to improve it, and check what people already did in this direction. For example, you can run two processes in parallel with concurrently.
I am new to js and I am trying to develop a simple node.js-mysql app. No matter what I do I can't get the standard
var express = require("express");
statement to work.
I have installed node.js and express correctly, express is in package.json. I have a local server running. But this simple line will not work.
On the node.js side at Windows command line I have no error but when I go to localhost:3000 on the browser, I get
'Uncaught Error: Module name "express" has not been loaded yet for
context: _. Use require([])' error at js console.
I tried changing it to
require(['express']`, function (express) {}
as suggested at node.js web site but then at the Windows command terminal I get a different error saying like
'expecting a string but received an array....'.
I have tried import instead of require and I have tried every suggestion that I could find on the Internet. I have been blowing my brains for weeks to get this to work with no success. I am so frustrated that I am seriously thinking about giving up all together. If someone can help I will be forever greatfull to him/her.
My main js code is as follows:
var port = 3000;
// Import or load node.js dependency modules.
var express = require("express");
var app = express();
var path = require("path");
var bodyParser = require("body-parser");
app.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies.
app.listen(port, () => {
console.log(`server is running at http://127.0.0.1:8887`);
});
app.get('/', function(req, res){
res.sendFile("D:/Behran's files/Web projects/havuzlusite/index.html");
});
Require.JS is for loading AMD modules (and is, honestly, obsolete in today's JS landscape).
Node.js modules are either ECMAScript modules (which use import and export) or CommonJS modules (which use require and module.exports).
Even though both AMD and CommonJS modules use a function named require they are not compatible.
There are methods you can use to run ES modules and CommonJS modules in the browser however they can't replace APIs that are provided by runtimes.
Express.js needs to be able to listen for incoming HTTP requests. Browsers do not provide any mechanism to make that possible. Node.js does.
If you want to run Express.js you have to run it using Node.js and not a browser.
Express.js creates an HTTP server. A browser can make requests to it (e.g. if you type http://127.0.0.1:3000 into the address bar.
(Your code says server is running at http://127.0.0.1:8887 but the port constant is set to 3000).
All your Express.js code must run through Node.js.
You can't send a copy of that code to the browser and run it there too.
I'm getting this error while trying to create/import a Client instance to connect to a local DB, (PGADMIN).
import {Client} from '/node_modules/pg/lib/'
Error
My Directory
Last part of my index.html
I've tried many types of urls but I can't get it done. So I'm asking for help.
Also, I've tried: const {Client} = require('pg'), but I get the "Uncaught ReferenceError: require is not defined"
Thanks.
You have two problems here.
/node_modules/pg/lib/ is going to resolve to an HTML document listing the files in that directory. You can only import a JS file.
Any library that allows you to directly connect to a postgresql database is going to depend on APIs provided by Node.js and which are not available in a browser, so even if you imported the correct URL, it still wouldn't work.
Connect to the database from server-side code and use it to provide the client with a webservice that you can access with Ajax.
Also, I've tried: const {Client} = require('pg'), but I get the "Uncaught ReferenceError: require is not defined"
Browsers don't have native support for CommonJS modules.
I am going to learn Node.js and right now I was trying to make a small demo project which implements an HTTP REST service.
My idea is to divide the APIs (url) by Resources and end up in a structure like the following one:
- user
> index.js
> post.js
> put.js
> delete.js
> functions.js
- person
> index.js
- index.js
So, if you are familiar with ASP.NET Web Api, I am trying to make every module of Node.js a Controller and every web method a single file (.js), in order to have an high maintainability in the future.
Question
Right now, my index.js file return the following:
var http = require('http');
var server = http.createServer();
How can I configure a specific "Request Handler" in each file by using this module? At the moment the createServer() method return a server object can use a single server.on('request', function) while I need to handle each request in a different file.
Go ahead learning with the help of some framework. They provide scaffolding of project.
If you are developing a complete web app(MVC) then go for ExpressJs or SailsJs
If you are looking out to develop only API(No Views) then go for Strongloop or Restify
There are many more frameworks but the above ones are popular.
I am building a real time chat application .i am using socket.io & node.js
This is my sever.js file ..
var socket = io.connect('http://localhost:81');socket.on('connect', function({alert('connection established');});
and my path information is
<script src="http://localhost:81/socket.io/socket.io.js"></script>
now when i look into directory i saw the socket.io.js path is node_modules/socket.io/lib/socket.io.js
if i change my path like
<script src="http://localhost:81/node_modules/socket.io/lib/socket.io.js"></script>
then am getting 404 error. else iam getting GET http://localhost:81/socket.io/socket.io.js net::ERR_CONNECTION_REFUSED
Just use it like this: <script src="/socket.io/socket.io.js"></script>
Paths inside of node_modules are not hosted to be available from browser.
Why not use express app to create the server?
And why not refer to their official documentation: http://socket.io/get-started/chat/