This question already has answers here:
Nodejs HTTP Createserver - unpredictable javascript execution while serving from html files
(1 answer)
Basic static file server in NodeJS
(8 answers)
Closed 4 years ago.
I created the simple server using nodejs and let it call html file which calls iquery. But it does not work with the browser showing the below two errors.
1. "Uncaught SyntaxError: Unexpected token <"
2. "Uncaught ReferenceError: $ is not defined at (index):13"
(Server side code)
var app = require('http').createServer(handler);
var fs = require('fs');
app.listen(1337);
function handler(req, res){
fs.readFile('index_test1.html', function(err, data){
if(err){
res.writeHead(500);
return res.end("Error");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}
(index_test1.html code)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo1</title>
<script src="jquery-3.3.1.min.js"></script>
<style type="text/css"></STYLE>
</HEAD>
<BODY>
<p id="test"></p>
<script>
$(function(){
$('#test').text('Hello World!');
});
</script>
</BODY>
</HTML>
jquery-3.3.1.min.js is in the same folder where the server.js and index_test.html exist.
I hope someone help me out on this issue.
Thanks,
There is one interesting thing happening with the code you have written. You are serving one file (index_test1.html) for every request right? Because you have hardcoded it in the handler.
So what is happening is when you're opening localhost:1337 you can see the index_test1.html file.
Now, in that html you import one jQuery file. But guess what, you only have ONE handler and that localhost:1337/jquery-3.3.1.min.js will go through the SAME handler and, YES! YOU GOT IT!, Serve the same exact index_test1.html file.
When you open the server in your browser open the Developer Tools and go to the Network tab. And refresh one more time to see the Network requests. You will see what I am talking about.
What you wanted to do is I guess making a Basic static file server in NodeJS (from #james' comment)? There are very good tutorials to make one out there. But I thought your problem was interesting so I explained it here. Hope this clears up some things for you.
Related
Overall problem: How to do a simple REST API call in javascript when a button is clicked
I want to do the equivalent of this REST call but in javascript
curl -X GET \
https://www.mydog.com/api/v3/user \
-H 'Authorization: Bearer 1234'
Attempted solution that doesn't work
page.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Submit</title>
</head>
<body>
<script src="submit.js"></script>
<button onclick="apicall()">Make REST API call</button>
</body>
</html>
submit.js
const axios = require('axios').default;
function apicall() {
console.log("apicall called");
const headers = {
"Authorization": "Bearer 1234",
}
axios.get(
"https://www.mydog.com/api/v3/user",
{headers: headers}
).then(function (response){
console.log(response)
}).catch(function (error) {
// handle error
console.log(error);
}).then(function () {
// always executed
});
Problem with attempted solution
Opening page.html and clicking the button shows this in the console: submit.js:1 Uncaught ReferenceError: require is not defined
Answer to subproblem (but feels not straightforward)
Client on Node.js: Uncaught ReferenceError: require is not defined
Never doing web programming before (but many years in algorithm / applied math type of programming) I'm wondering if I'm getting off track. This answer seems helpful except isn't making an http request something simple that's built into every language? Should I be using something beside axios maybe? What's the simplest way to do a client javascript side http call? Or am I asking the wrong question and need to do backend javascript for this?
This usually happens because your JavaScript environment doesn’t understand how to handle the require() function reference. The require() function is only available by default on Node.js environment.
there are several ways to get work around. You can use requireJS or browserify for this. Please check require for browsers
If you want to make a REST API call, you can use XMLHttpRequest instead of Axios
Browers have the fetch API in-built which can be used to make API calls.
Check out the docs here:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
For browser you should get axios from a cdn
So add <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> in your html file before the submit.js (the order is important, so that you get axios first then you use it) And remove the require in submit.js
require is for nodejs, you use a package manager to download the package locally, then you can import it using require, while in the browser you don’t have that option.
I'm pretty new to web-dev and have currently been struggling with a bug for multiple days that I honestly have no clue how to resolve/have no idea what could be causing it. At this point I've exhausted what I think could be causing the problem, so any insights would be greatly appreciated!
I am running an Apache webserver through the Flask Python framework. My client-side JS (app2.js) is as follows:
// set up basic variables for app
var socket;
$(document).ready(function() {
socket = io.connect('https://' + document.domain + ':' + location.port+'/main');
console.log(document.domain);
console.log("Document ready");
socket.on('disconnect', function() {
console.log("disconnecting...");
});
console.log("Simple logging");
});
Further I have reduced my .html page that loads the above script to the following:
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
<script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script src="{{ url_for('static', filename='scripts/app2.js') }}"></script>
</html>
When I load my page, I will see the following printed in the Chrome console:
Document ready
Simple logging
GET https://DOMAIN/socket.io/?EIO=3&transport=polling&t=1465632212131-2&sid=d4082f4636fd4d04a5dcc4b660ee5b2a 400 (BAD REQUEST)
disconnecting...
POST https://DOMAIN/socket.io/?EIO=3&transport=polling&t=1465632212141-3&sid=d4082f4636fd4d04a5dcc4b660ee5b2a 400 (BAD REQUEST)
I have no clue what the source of these malformed GET/POST requests are, but as a consequence of them, my page becomes non-functional. If I refresh the page, I sometimes won't get these errors. Other times, I refresh the page and still get the same error logs and then if I stay on the page long enough, I get more GET/POST errors of the same flavor and a "disconnecting" message sprinkled in.
It's the lack of reproducibility that is throwing me off, and I'm not sure what else to consider/how to go about fixing this. I've tried to reduce the client-side .html/.js files to the bare minimum to see what could be wrong and for some reason the code is still failing. I would be happy to provide any additional information that would help pinpoint what is going on.
Thanks!
Am writing my first websocket program and am getting "WebSocket handshake: Unexpected response code: 404", error while loading the webpage.
I am using JDK 1.7 and jboss 8 (wildfly8.0).
Could anyone please assist?
window.onload = init;
var socket = new WebSocket("ws://localhost:8080/WebsocketHome/actions");
socket.onmessage = onMessage;
and head in html
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="websocket.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
Thank you guys for your suggestion, I found the answer.
The code I copied is from http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html site.
The problem was the url as mentioned in the js file and the project name they are proposing is WebsocketHome. I had changed the project name to Websocket thus my url should be ws://localhost:8080/Websocket/actions.
Thanks for your support.
Actually, the problem here is case-sensitivity in the URLs. You did not need to change the project name. Just changing the Websocket URL in JavaScript file to
ws://localhost:8080/WebSocketHome/actions
(with capital S, as in the project name) would have solved the problem. In your case, changing both of them removed the case inconsistency, so it worked.
It's because of the issue of /info=34424 - with 404 error - that I had to abandon using the xml approach suggested at other places. I have Spring 4.2 in my project and many SockJS Stomp implementations usually work well with Spring Boot implementations. This implementation from Baeldung worked(for me without changing from Spring 4.2 to 5). After Using the dependencies mentioned in his blog, it still gave me ClassNotFoundError. I added the below dependency to fix it.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
Baeldung's implementation curiously does not make any such calls
flow/websocket/add/info?t=1540813753999
What it does (on send and receive) is below. I am only pasting it in case people well-versed with these libraries can further add insights on this forum.
>>> SEND
destination:/app/chat
content-length:38
{"from":"nicholas","text":"try again"}
<<< MESSAGE
destination:/topic/messages
content-type:application/json;charset=UTF-8
subscription:sub-0
message-id:m3p096zk-11
content-length:53
{"from":"nicholas","text":"try again","time":"13:46"}
My guess is that you are trying to contact the websocket with a normal browser.
That is not allowed and gives a 404 error. You need to use a script or curl to address websockets.
i am using requires.js 2.0. I have the following simplified use case:
my HTML file:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script type="text/javascript" data-main="apptest.js" src="../_js/libs/require/require.js"></script>
</head>
<body>
</body>
</html>
And then in apptest.js:
requirejs.config({
paths: {
'text': '../_js/libs/require/text'
}
});
requirejs(
['text!boxes.html'],
function (Boxes) {
alert("done");
}
);
Ok, so it doesn't really do much, but enough to make my point. Only in Firefox (14.0.1) i get an exception "uncaught exception: java.security.AccessControlException: access denied (java.io.FilePermission .\boxes.html read)".
So, require.js successfully loaded the text plugin, but fails loading my html file, which i want to use as a template later on. In Google Chrome and even IE9 it works just fine. I am on Windows 7.
I am running this on a local webserver, so no file://... requests here.
I have checked, if i have any special permissions set on the html file, but have not found anything suspicious.
Anyone have an idea?
Update: Running the test in Firefox 13.0.1 does actually work for me without errors. So could it be, that this is a bug, that has been introduced in firefox 14?
I was having the same problem a minute ago. I've fixed it by doing the following in the main.js file (where you setup the config)
Before the
require.config({.....
add the following code:
Packages = undefined;
This should do the trick.
You should have something like this:
Packages = undefined;
require.config({
baseUrl: theAppBaseUrl,
paths: {
Basically the explanation is that it is trying to use Java to get the file instead of an ajax request (for whatever reason). This forces it to use an XHR object to fetch it.
Cheers!
// Server.js
var http = require('http');
var path = require('path');
var fs = require('fs');
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
if (filePath == './')
filePath = './index.html';
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(content, 'utf-8');
}
});
}
else {
response.writeHead(404);
response.end();
}
});
}).listen(8125);
console.log('Server running at http://127.0.0.1:8125/');
// index.html
<html>
<head>
<title>Rockin' Page</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
</head>
<body>
<p>This is a page. For realz, yo.</p>
</body>
<script type="text/javascript">
$(document).ready(function() {
alert('happenin');
});
</script>
</html>
I am able to run my static page, but i have couple of questions down the line.
What do i do next? i mean what to develop and what to learn? i am confused.. what is the difference i am doing with my current webserver.
Is node.js just an replacement of my Apache Webserver.
Can anyone clearly explain me the main purpose of nodejs
node.js is a platform (language, library, and interpreter), and Turing-complete, i.e. you can do anything with it. Most likely, you'll want a web application which is interactive in some way. Have a look at examples like a chat room. There are also lots of other resources on how to get started.
In the end, it's up to you what you want your site to be. A chatroom? A forum? A search engine? A multiplayer game? If you just want to transfer static files (i.e. have no need for server state or communication between clients), there's no need to use node.js.
Questions
What do i do next? i mean what to develop and what to learn? i am confused.. what is the difference i am doing with my current webserver.
Is node.js just an replacement of my Apache Webserver.
Can anyone clearly explain me the main purpose of nodejs
Answers
Start with some simple examples and/or tutorials. I've forked Mastering Node on github, which is a quick read but is also still a work in progress. I've used expressjs for quickly creating static sites (like my online resume). I also use node.js and nodeunit for testing JavaScript or performing scripting tasks that could otherwise be done in bash, php, batch, perl, etc.
node.js gives an IO wrapper to Google's V8 JavaScript engine. This means that JavaScript is not bound to a web browser and can interact with any type of IO. That means files, sockets, processes (phihag's Turing-complete answer). It can do pretty much anything.
The main purpose of nodejs is that IO code is evented and (mostly) non-blocking. For example, in ASP.NET, when a web server receives a request that request's thread is blocked until all processing is complete (unless processed by an asynchronous handler, which is the exception not the rule). In node.js (express, railwayjs, etc.), the request processing is handled by events and callbacks. Code is executed asynchronously and callbacks are executed when complete. This is similar to the asynchronous pages of ASP.NET, the main difference being that node.js and web frameworks on top of it don't create millions of threads. I believe the threading issue is discussed in Ryan's video.
here is an excellent video from nodejs creator ryan ... http://www.youtube.com/watch?v=jo_B4LTHi3I
it explains what it is with code examples it is really good.
here are some more resources that you can take a look at
http://blog.jayway.com/2011/05/15/a-not-very-short-introduction-to-node-js/
http://www.nodetuts.com/
http://www.howtonode.org/