Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Dennis Klarenbeek
Dennis Klarenbeek
17,168 Points

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.

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

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?

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:

```javascript
app.factory('dataServices', function($http) {
  return {
    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
      })
    },```

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

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