简体   繁体   中英

POST, PUT, DELETE requests from AngularJS $http/AJAX to Node.js + Express.js based API

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?

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 eg 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' } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM