0

As I said on title I'm trying to store the inputs the user made on an HTML form using fs from node to store it on a JSON file.

What I'm trying to save is a key value pair which would look like this:

{
  fName: example,
  lName: example,
  email: example,
  pswd: example
};

But what I'm getting is:

{ '[object Object]': '' }

I got two files working with this, one which verify the inputs and makes an AJAX call if everything is fine and another one which handles the HTTP request and saves the data on the JSON file.

Here, the AJAX call:

let formElement = {
        fName: firstName,
        lName: lastName,
        email: email,
        pswd: pswd
      };
var request = new XMLHttpRequest();
request.open('POST', './signUp.js');
request.setRequestHeader("Content-type", "application/json");
request.send(formElement);

And here the code which manages the HTTP request:

collectReqData(req, res => {
  let data = JSON.parse(JSON.stringify(res));
  fs.writeFileSync('signUp.json', data);
});

I've also tried doing let data = JSON.stringify(res); but I'm getting the same response.

If someone could help me I'll be really glad, I'm stuck with this and I don't know what to do.

7
  • 1
    fs.writeFileSync('signUp.json', JSON.stringify(data)); Commented Jan 2, 2020 at 20:54
  • @AdamH I've try that but it doesn't work, the output is still the same Commented Jan 2, 2020 at 20:58
  • 1
    @FacuCarbonel it should be: "fName": "example" - close its key/value with double quotes and execute again JSON.stringify(res). Commented Jan 2, 2020 at 21:02
  • 1
    app.post('/', function (req, res) { // get the request parameters let params = req.params; // write the params to a file fs.writeFileSync('signUp.json', JSON.stringify(params)); // write your response using res.send res.send({sucess: true}); }) Commented Jan 2, 2020 at 21:04
  • 2
    Where's the code where you're invoking collectReqData? Also, you should not be synchronously writing to a file in this context as you will be blocking the thread for other requests. Commented Jan 2, 2020 at 22:09

2 Answers 2

1

Can't recreate your server code behavior. Not enough information. But @jfarleyx answer looks legit to me. Except that you probably do not use express framework, judging by the look of collectReqData(). Never the less, the root issue is with the client code: you should change request.send(formElement); to request.send(JSON.stringify(formElement));

Updated to reflect on comments After looking into repl.it I see that your problem is not with the code in the question, but exactly with the skipped code. Specifically with collectReqData() and collect() I do not know how you want them to be/ so I fixed the code my way, using body-parser and not trying to be fancy. You can check correctly working code at https://repl.it/repls/SadCulturedFormat

Sign up to request clarification or add additional context in comments.

2 Comments

That's right there is almost no info about the server because I'd tried to put just the code where I'm getting the problem, but you can see it working at repl.it/@f2bear/FormData-save-with-NodeJs, the only thing I ask if anybody is going to enter here is to not modify anything because I'm trying to learn with this and it will be counterproductive if anyone except myself modify something here
Thank you very much!! that solved my problem, the output it's exactly as what I wanted
1

OP has clarified that they are using Express in their web application, but isn't using anything to process the incoming JSON. I recommend using the body parser library to process the incoming JSON. Here is an example...

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

app.use(bodyParser.json());

Edit: It looks like you're using Express v4, so you can bypass using bodyparser and use express to process JSON...

app.use(express.json());

You should read the req value, not the res value. Like this...

let data = req.body;

Then, write the JSON data to your file...

collectReqData(req, res => {
  fs.writeFileSync('signUp.json', req.body);
});

Also, I recommend adding error handling & returning a response from your method. Like this...

collectReqData(req, res => {
  try {
    fs.writeFileSync('signUp.json', req.body);
    res.status(200);
  } catch (err) {
    res.status(500).json(err)
  }
});

5 Comments

Thanks for the help, I had just tried what you're saying and the output I get is undefined for some reason
@FacuCarbonel req.body was undefined or req was undefined? Can you print what req contains by doing console.log(req)? Are you using Express as a web server in your server side code?
req.body trows undefined. I would love to share here what prinst if I do console.log(req) but It's way too long for this plataform but in summary it shows a lot of data about the request including host, status, data types and other things, it's like 2000+ lines
@FacuCarbonel I see now from your code that you posted online that you are indeed using Express. You should install the bodyparser library and use that to process the incoming JSON data. I'll enrich my answer below with code on how to do this.
Thank you very much, this helps a lot. the answer which solved my problem was from @x00 but your's helped me with error handling and it comes with lot of knowledge that I really appreciate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.