简体   繁体   中英

Can't get the PUT method working (Express & Angular)

I've made an REST Api and a client side framework with the MEAN Stack. After working local I deployed the API on Heroku. In my Express routes I handle the res.headers so that CORS should be working:

app.use('*', function(req, res, next){
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  if(req.method === "OPTIONS") {
    res.header("Acces-Control-Allow-Methods", "GET, PUT, POST, DELETE");
    return res.status(200).json({});
  }
  next();
});

In the client side I handled the req headers:

app.factory('dataServices', function($http) {
  return {
    //Get the location information from API
    getAll: function() {
      return $http({
        method: 'GET',
        url:  url
      })
    },

    get: function(id) {
      return $http({
        method: 'GET',
        url:  url + '/' + id
      })
    },
    post: function(id) {
      return $http({
        method: "POST",
        url: url,
        data: {}
      })
    },
    put: function(id, data) {
      return $http({
        method: "PUT",
        url:  url + '/' + id,
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Headers":  "Origin, X-Requested-With, Content-Type, Accept",
          "Access-Control-Allow-Method":  "PUT",
          "Content-Type": "application/json charset=UTF-8"
        },
        data: data
      })
    },

When I trigger the GET or POST request there are no problems. But when I try to trigger a PUT or DELETE method:

  $scope.saveLocation = function(id) {
    console.log(id)
    dataServices.put(id).then(function successCallback(repsonse) {
      $scope.customer = response.data;
    })
  };

I get the following error in my console:

XMLHttpRequest cannot load https://bbsalesapi.herokuapp.com/locations/580fd2a672e68a000352783a. Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

I tried to read more about the different http methods but I can't figure out why it's not working. Can somebody help me this one?

I usually put CORS stuff in middleware, ad it works for me...:

// middleware
var handleCORS = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
}

// ...

app.configure(function() {
  app.use(express.bodyParser());
  app.use(express.cookieParser());
  app.use(express.session({ secret: 'my super secret' }));
  app.use(express.methodOverride());
  app.use(handleCORS);
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

use cors library and it will solve the issue npm install cors --save

var cors = require('cors');

 app.use(cors())

For the PUT request it's mandatory to set Content-Length header.
Also your content Type has a problem , you forgot the ;

put: function(id, data) {
  return $http({
    method: "PUT",
    url:  url + '/' + id,
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers":  "Origin, X-Requested-With, Content-Type, Accept",
      "Access-Control-Allow-Method":  "PUT",
      "Content-Type": "application/json; charset=UTF-8",
      "Content-Length": Buffer.byteLength(data)
    },
    data: data
  })
},

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