0

I wrote backend API on Node.js and Express.js v4, this part (index.js):

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://example.com');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

app.post('/add1', function (req, res) {
    db.one("INSERT INTO table(value1) VALUES (${value1}) RETURNING ID", req.query).then(function (data) {
        res.json(data);
    }).catch(function (error) {
        res.json(error);
    });
});

app.put('/add2', function (req, res) {
    db.one("INSERT INTO table(value1) VALUES (${value1}) RETURNING ID", req.query).then(function (data) {
        res.json(data);
    }).catch(function (error) {
        res.json(error);
    });
});

app.get('/add3', function (req, res) {
    db.one("INSERT INTO table(value1) VALUES (${value1}) RETURNING ID", req.query).then(function (data) {
        res.json(data);
    }).catch(function (error) {
        res.json(error);
    });
});

And I have Angular JS or sample ajax like this

app.controller('globalController', function($scope, $http) {
    var jsd = {};
    jsd.value1=1;
    $http.put(API_URL + 'add2', jsd).then(function(data) {
        console.log(data);
    }, function(data) {
        console.log(data);
    });
});

and

$.ajax({
            url: API_URL + 'add1',
            method: 'POST',
            dataType: 'json',
            data: jsond,
            success: function(data) {
                console.log(data);
            },
            error: function(data) {
                console.log(data);
            }
        });

But I don't recive any data to my req.query and in generally in req object. When I make my AJAX request to add3 with get, then all works, req.query has my params.

I read about this solution:

app.config(function ($httpProvider) {
        $httpProvider.defaults.transformRequest = function(data){
            if (data === undefined) {
                return data;
            }
            return $.param(data);
        };
        $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    });

and solution here

var multer = require("multer");

//...

var upload = multer({ dest: "./upload/" });
app.post("/post", upload.array(), function(req, res) {
    console.log(req.body);
    res.send(null);
}

I tried first, not works, and second is too strange solution (I can't save data to files and etc.) I think problem was in fist OPTION request, but I googled it, not found solution. I need little example (working code) how I can send POST or PUT data from Angular $http or AJAX and use this data in req object in node.js. In GET requests all this works, but how I can make it work on others?

1 Answers1

1

Which version of Express are you using? It's possible that you're writing the old way and using the new version.

You might wanna check this out -- How to retrieve POST query parameters?

Anyway, I'd suggest you use ngResource for making REST HTTP calls in Angular.

  1. Instantiate the Factory This will expose a few methods e.g query, save etc.

angular
  .module('MyModule')
  .factory('AddEndpoint', AddEndpoint);

AddEndpoint.$inject = ['$resource'];

function AddEndpoint($resource) {
  return $resource(API_URL + '/:param', { param: '@param' });
}
  1. Enjoy The Factory

angular
  .module('MyModule')
  .controller('MyController', MyCtrl)
 
MyCtrl.$inject = ['AddEndpoint'];

function MyCtrl(AddEndpoint) {
  var scope = this;
  scope.getFromApi = AddEndpoint.get({ params: 'add1' }); // GET 'API_URL/add1'
  scope.postToApi = postToApi;

  function postToApi(data) {
    data.params: 'add2'
    AddEndpoint.save(data); // POST to 'API_URL/add2'
  }
}
rolodex
  • 558
  • 1
  • 7
  • 19
  • I use express 4 – Ali S. Veliyev Dec 01 '17 at 18:11
  • So you need `body-parser` as per the link I referred. `npm install --save body-parser` and import it in your `index.js` The rest you can follow on the guide in the link. Good luck, and have fun! – rolodex Dec 01 '17 at 18:13
  • Strange things happened, I add `app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json());` @rolodex Now in ajax post it works, ajax put not works, $http post/put both not works – Ali S. Veliyev Dec 01 '17 at 18:24
  • What? I cannot comprehend what you're trying to say...first you said `POST` work, then both `POST` and `PUT` does not? – rolodex Dec 01 '17 at 18:26
  • what you can't understand? – Ali S. Veliyev Dec 01 '17 at 18:31
  • Ok `$http` from Angular and `$.ajax` from jQuery. Let me re-comprehend. – rolodex Dec 01 '17 at 18:34
  • You should use `application/json` in your `$http` instead of `application/x-www-form-urlencoded`. That's why `$.ajax` works because you set it to send `json`. It seems like you need better understanding on how to make request and transforming the request's body...That is also the reason I recommend you to use `$resource` for Angular. – rolodex Dec 01 '17 at 18:40
  • changed, not works. and this is not explain why in ajax put not works too – Ali S. Veliyev Dec 01 '17 at 18:51
  • Change the method to `PUT` instead of `POST` in your `$.ajax`. If you'd like the angular method, please use `$resource` instead. It'll worth your time. – rolodex Dec 01 '17 at 18:53
  • 1
    After 1 day work I fixed problem, thanks. Part of your solution make help – Ali S. Veliyev Dec 03 '17 at 05:11
  • Perhaps you can share what went wrong by updating the post? At least it'll help others with the same problem. – rolodex Dec 04 '17 at 05:55