[javascript] JS file gets a net::ERR_ABORTED 404 (Not Found)

I am trying to create a simple Io-web-chat. I recently wanted to seperate my <script> inside my html file to an external js file.

this is my very simple folder structure:

Chat
|-- index.html
|-- index.js
`-- server.js

Relevant part of html file:

<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script src="index.js"></script>
</body>
</html>

Relevant part of index.js file:

$(function() {

  //Initialize variables
  var $messageArea = $('#messages');
  var $InputMessage = $('#InputMessage');
  var $InputName = $('#InputName');

  //Initialize Socket
  var socket = io();

  //Send server Your message
  socket.emit('chat message', $InputMessage.val());

});

Relevant part of server.js file:

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

I also tried putting my files in this public type structure that they have on the socket.io examples:

Chat
|-- Public
|   |-- index.html
|   `-- index.js
`-- server.js

in that case I changed: src="/index.js" in html added /public/index.html into the server.js file But no luck.

This is all running in localhost. What am I doing wrong here?

This question is related to javascript sockets

The answer is


As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

Questions with javascript tag:

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax Drag and drop menuitems Is it possible to execute multiple _addItem calls asynchronously using Google Analytics? DevTools failed to load SourceMap: Could not load content for chrome-extension TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app What does 'x packages are looking for funding' mean when running `npm install`? SyntaxError: Cannot use import statement outside a module SameSite warning Chrome 77 "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 Why powershell does not run Angular commands? Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop Push method in React Hooks (useState)? JS file gets a net::ERR_ABORTED 404 (Not Found) React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block Can I set state inside a useEffect hook internal/modules/cjs/loader.js:582 throw err How to post query parameters with Axios? How to use componentWillMount() in React Hooks? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once Objects are not valid as a React child. If you meant to render a collection of children, use an array instead How to reload current page? Center content vertically on Vuetify Getting all documents from one collection in Firestore ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How can I add raw data body to an axios request? Sort Array of object by object field in Angular 6 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Axios Delete request with body and headers? Enable CORS in fetch api Vue.js get selected option on @change Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) Angular 6: How to set response type as text while making http call

Questions with sockets tag:

JS file gets a net::ERR_ABORTED 404 (Not Found) mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 TypeError: a bytes-like object is required, not 'str' Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED No connection could be made because the target machine actively refused it 127.0.0.1 Sending a file over TCP sockets in Python socket connect() vs bind() java.net.SocketException: Connection reset by peer: socket write error When serving a file How do I use setsockopt(SO_REUSEADDR)? Socket.io + Node.js Cross-Origin Request Blocked Chrome hangs after certain amount of data transfered - waiting for available socket How to increase MySQL connections(max_connections)? Why is my method undefined for the type object? Sending string via socket (python) "An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP centos: Another MySQL daemon already running with the same unix socket Java simple code: java.net.SocketException: Unexpected end of file from server socket.error:[errno 99] cannot assign requested address and namespace in python htons() function in socket programing Client on Node.js: Uncaught ReferenceError: require is not defined How to connect to a remote Windows machine to execute commands using python? Python send UDP packet "A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient Python Socket Receive Large Amount of Data How to find my php-fpm.sock? How do I debug error ECONNRESET in Node.js? java.net.SocketTimeoutException: Read timed out under Tomcat Differences between TCP sockets and web sockets, one more time What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs? Understanding INADDR_ANY for socket programming Why am I getting the error "connection refused" in Python? (Sockets) How do I remove a CLOSE_WAIT socket connection An attempt was made to access a socket in a way forbidden by its access permissions Bind failed: Address already in use What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK] How do SO_REUSEADDR and SO_REUSEPORT differ? What can cause a “Resource temporarily unavailable” on sock send() command C# An established connection was aborted by the software in your host machine What is the correct way to read from NetworkStream in .NET Errno 10061 : No connection could be made because the target machine actively refused it ( client - server ) Connecting to TCP Socket from browser using javascript Handling a timeout error in python sockets Python socket.error: [Errno 111] Connection refused socket.emit() vs. socket.send() Bad File Descriptor with Linux Socket write() Bad File Descriptor C TCP: can two different sockets share a port? Python Socket Multiple Clients What does it mean to bind a multicast (UDP) socket? an attempt was made to access a socket in a way forbbiden by its access permissions. why?