1

I am trying to send data from my html for node.js Express using a post method.

Using this code on my html file:

function readfile() {
var data = {};
data.path = '/home/test/pgadmin.txt';
data.ext = '.txt';
console.log(data);
  $.ajax({
    url: '/read_file',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(data),
    success: function(data) {
      console.log(data);
    }
  });
}

And this is the code that I'm using on server side.

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

app.post('/read_file', function(req, res) {
   console.log(req.data.path) //?
   console.log(req.data.ext) //?
   //I dont know how to get the values of my data: here

})

Is there some way to get those data values without using bodyparser?

6
  • the point of bodyparser is to be able to parse the request body - why don't you want to use bodyparser? look at the source code to body-parser and duplicate it ... or just use body-parser Commented Apr 26, 2017 at 0:56
  • Is it just parsing the body of request or of the entire html body? Commented Apr 26, 2017 at 0:58
  • 1
    npm install body-parser then app.use(require("body-parser").json()) before your route Commented Apr 26, 2017 at 0:59
  • body-parser has nothing to do with the html <body> at all Commented Apr 26, 2017 at 0:59
  • How could I make it using body-parser? Commented Apr 26, 2017 at 1:00

1 Answer 1

3

I'm not sure why you don't want to use bodyParser, but this could be done like:

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

app.use(bodyParser.json());

app.post('/read_file', function(req, res) {
   console.log(req.body);
});

Of course you have to install bodyParser npm module as Brian pointed out.

See How do I consume the JSON POST data in an Express application

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

Comments

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.