Matt Keefe
Matt Keefe

Reputation: 3

Turning single-page app into Express app, problems with AJAX and .json file

I have a very simple single-page app (consisting of an index.html, style.css, functions.js and data.json) which I'm trying to turn into an Express/Node.js app to add some additional functionality. I am new to Node.js.

I've done this by creating an app.js file which includes the following code:

var express = require('express');
var app = express();
var path = require('path');

// viewed at http://localhost:8080
app.use(express.static(__dirname + '/public'));

app.listen(8080);

The basic app files are all in the /public folder, so this works just fine. The only part that doesn't work anymore is the POST request, an AJAX function in functions.js, which fetches data.json. This now returns a 404.

Now, I can fetch data.json into app.js by adding the following code to app.js:

var testData = require("./public/data.json");
console.log(testData);

This works just fine and logs to console, so it's working and I know it's finding the file, but the data isn't available to any of the functions in my functions.js file. I'm guessing this is because it's on the server side, whereas the AJAX request would have brought it client-side. Like I say, I'm new to Node.js and Express, and this is pretty much where my understanding runs out.

So, my question is, how do I replicate the functionality of the AJAX POST request I had in my functions.js file? Is it just the case that I need to put my data.json file somewhere else, or set up another route? Or do I need to be moving more of this functionality over to the app.js file, and somehow using the variable created there (which now contains all the data from data.json) on the client-side? If so, how do I go about that?

I appreciate this is a broad question - I'm not necessarily after complete code to provide a solution (if that's laborious); pointers on where to look and how I should be doing this would be just as helpful. I'm happy to do my own research when I know where to look - which, right now, I don't.

Any help is much appreciated. Thanks.

Upvotes: 0

Views: 111

Answers (1)

Anatol - user3173842
Anatol - user3173842

Reputation: 1415

Use a GET instead of a POST request to fetch static data. You are getting a 404 because your express app does not handle post requests for the requested url.

If you want to serve dynamic data you can do the following:

app.post('/data.json', function(req, res) {
  var data = {};
  data.something = 'whatever';
  res.json(data);
});

Upvotes: 1

Related Questions