Search code examples
javascriptnode.jswebhttpserver

Communication with an http-server


I have some data that I want to store locally and to be able to pull it dynamically, maybe in another session or after the browser was closed and all browser data was cleared.

I run the site with http-server CLI command and navigate to localhost to access it from the browser.

How can I send data to the server side so the server side will save the data as a file?

I tried to do an ajax post request to see if something happens in the console, but it just returned 404 and nothing came up in the console.

The docs don't mention anything about post requests: https://www.npmjs.com/package/http-server

PS: I have to run this with http-server, this is an offline project.


Solution

  • You will not be able to do this with http-server alone, because http-server can only serve static content and cannot be used to run any code on the server side.

    You will have to write a backend yourself, possibly using a framework like Express, Hapi, Restify, Loopback etc. and serve your static files that you need with your new backend, or keep it served as you do now but then you will probably need to take CORS into account if you use different ports for your data saving/retrieving endpoints and your static content - unless you run a reverse proxy that makes it all appear on the same host name and port.

    You can use the file system to save the data or you can use a database - either a standalone database like Mongo or Postgres or an embedded database like SQLite or Loki.

    For examples on how to serve static content in your own backend see: