0

I am currently trying to post json data to a json file. In order to do so, I've setup a NodeJS and express server but something keeps messing up. I keep receiving this feedback:

jquery-3.2.1.js:9566 POST http://localhost:3000/Alpha/json/details.json 404 (Not Found)

I read several other questions stating that the issues is probably in my server side script and that I haven't specified the json file correctly.

JS Client Side Post script:

function sendFormData(){
            var formData = JSON.stringify($("#myForm").serializeArray());

            $.ajax({
                type: "POST",
                url:"../json/details.json",
                data: formData,
                success: function(){
                    alert("something!");
                }
            });
        } 

My HTML Form:

<form action="XXXXXXXX"id="myForm"><label for="id">ID</label>
    <input type="text" id="id" name="id" placeholder="Item ID number" ng-model="newDetails.id">

       <label for="system">System</label>
       <input type="text" id="system" name="lastname" placeholder="Type of System" ng-model="newDetails.system">

       <label for="date">Date</label>
       <input type="text" id="date" name="lastname" placeholder="dd-mm-yyyy"  ng-model="newDetails.date">

       <label for="priority">Priority</label>
       <select id="priority" name="priority" ng-model="newDetails.priority">
         <option value="high">High</option>
         <option value="medium">Medium</option>
         <option value="low">Low</option>
        </select>
        <label for="description">Description</label>
        <textarea class="form-control" rows="3" id="desc" name="description" ng-model="newDetails.description"></textarea>

        <label for="priority">Status</label>
        <select id="status" name="status" ng-model="newDetails.status">
          <option value="OPEN">OPEN</option>
          <option value="ON HOLD">ON HOLD</option
          <option value="CLOSED">CLOSED</option>
        </select>

       <input type="button" value="Submit" class="btn" data-dismiss="modal" style="background-color:#FFBE00; color:#002244;" onClick="sendFormData()">
</form>

NodeJS Script:

    var express = require('express');
    var app = express();
    var bodyParser = require('body-parser');
    var path = require('path');

    app.use(bodyParser.json());
    app.use('../json', express.static(path.join(__dirname, 'json')));
    app.use('/', express.static(__dirname + '/'));


    app.post('/formdata', function(req, res) {
        console.log( req.body.id + req.body.system + req.body.date + req.body.priority + req.body.description + req.body.status);
        res.send("ok");
    });

    app.use(bodyParser.json());

    // Get information submitted
    app.post('/', function(req, res) {
        console.log("Information received !");
        console.log(req.body);
        res.send("Ok!");
    });

app.listen(3000);

Is my Node Script working fine? Why cannot I find the json file?

root/Alpha/json/details.json - is the json file path

my node script is in the root directory

User199932
  • 86
  • 12
  • `..` has special meaning in paths. – Kevin B Apr 28 '17 at 15:21
  • @KevinB I know, it goes one directory up. That's why I use it, I've tried it even without the two dots. – User199932 Apr 28 '17 at 15:22
  • 1
    What looks wrong to me is how you've used it in the app.use. The path you're using to access the json doesn't match `../json` – Kevin B Apr 28 '17 at 15:23
  • how should I change it? – User199932 Apr 28 '17 at 15:27
  • I dunno. What did you intend for it to be? I'd suggest using a route path that matches the route you want the client to use to access said static files. I have no idea what you intended `../json` to indicate. – Kevin B Apr 28 '17 at 15:27
  • _root/Alpha/json/details.json - is the json file path_ as I've said in the question. I need to write to that file. – User199932 Apr 28 '17 at 15:29
  • So why not use `/json`? what was the purpose of the `..`? i feel like i'm missing some important piece of information. – Kevin B Apr 28 '17 at 15:29
  • @KevinB because I obviously have messed up the paths and I'm not sure how to set them. Even when I remove the dots, I yeld the same result.. – User199932 Apr 28 '17 at 15:30
  • the url in your ajax request should be the url to your node service, not the path to your json file. – mrdeleon Apr 28 '17 at 15:34

1 Answers1

1

I see that you are confused with many things here. I think you should step back and learn about absolute and relative URLs before you'll be able to understand how to fix your code. The advice on how to fix it is below but it will serve you no good if you just blindly apply the advice. You need to learn why you need to do the things below or otherwise you will face more problems later. Read about URLs, paths and HTTP:

Read at least the basic info on how absolute and relative URLs are constructed, what is sent as path in HTTP requests, how to traverse the file system and what /, .. and . mean.

Now, to the solution.

This makes no sense:

app.use('../json', express.static(path.join(__dirname, 'json')));

because you cannot serve a URL that is one level up the root path.

When you access ../x/y.json from the client side when you are on a page e.g. http://www.example.com/a/b/c/index.html then what the client will request is actually http://www.example.com/a/b/x/y.json and this is what you need to serve on the backend side. What file you actually serve is a different story, but this is a route that you need to serve.

I think you need to rethink:

  1. what ., .. and / mean in relative URLs
  2. what actual URL you want to serve - it can be anything but your client and server must agree on it

What would make sense would be:

app.use('/json', express.static(path.join(__dirname, 'json')));

but it would be redundant if you serve the __dirname anyway and it already includes the json directory:

app.use('/', express.static(__dirname + '/'));

By the way the above could be just:

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

but it is not recommended (and needed) to serve your backend files. You should put all of your static content in one directory e.g. called static or public or html or whatever and serve this directory with:

app.use('/', express.static(path.join(__dirname, 'static')));

and put your json directory inside of that directory.

For more info and examples on how to properly serve static content, see the following answers:

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177
  • this is only making it a bit more confusing for me. I don't have that much experience using NodeJS.. – User199932 Apr 28 '17 at 15:38
  • @User199932 This is not that complicated. See the first example in [this answer](http://stackoverflow.com/questions/5823722/how-to-serve-an-image-using-nodejs/40899767#40899767). You can download it [from here](https://github.com/rsp/node-static-http-servers). Just put a `json` directory in the `public` directory that is there and whatever you put into `json` you will be able to access with `http://localhost:3000/json/xxx.json` where `xxx.json` is the file that you put there. See the examples in the links in my answer. Everything is there with working examples, you just need to put your files. – rsp Apr 28 '17 at 15:44
  • Thank you, I will check it out. – User199932 Apr 28 '17 at 15:54