2

My middleware code:

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

Every time that I've found someone with the same error message, the response that rectifies their problem involves telling them to set "Access-Control-Allow-Methods" just like I have it.

My delete method on the front end:

deleteSaved(url) {
    // return axios.delete("https://api.mlab.com/api/1/databases/etc.", {
    //  params: {
    //      "url": url
    //  }
    // })
    // .then(function(results) {
    //  console.log("axios results", results);
    //  return results;
    // });
    return fetch("/saved", {
        method: 'DELETE',
        body: JSON.stringify({url: url}),
        mode: 'cors',
        cache: 'default'
    }).then(function(response) {
        return response;
    }).then(function(data){
        console.log(data);
        return data;
    }); 
}

I have both fetch and axios there because I thought I was having trouble with the axios delete method. In the development server, both calls work properly.

In the axios method, I have my db API URL for the sake of simplicity (to make it easier to get things to work); in the fetch method, I have '/saved' because when I asked this question last time, someone commented and suggested that I proxy all DB requests through my express server rather than having the browser connect directly. I tried a few things (setting "proxy" and "https_proxy" to my mlab api url in the package.json associated with the create-react-app front end), but I don't think I really understand what that means. The proxy didn't work (the "/saved" would result in an error for a GET request at the apps URL + /saved rather than for the mlab API url) and I simply can't find anything on google about proxying requests to the DB through the express server.

My response headers:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:POST,GET,OPTIONS,PUT
Access-Control-Allow-Origin:https://nyt-mern-app.herokuapp.com
Access-Control-Max-Age:1728000
Allow:POST,GET,OPTIONS,PUT
Cache-Control:no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Length:0
Content-Type:text/html;charset=UTF-8
Date:Thu, 26 Oct 2017 19:34:08 GMT
Expires:Tue, 01 Feb 2000 08:00:00 GMT
Keep-Alive:timeout=5, max=99
Last-Modified:Thu, 26 Oct 2017 19:34:08 GMT
Pragma:no-cache
Server:Apache/2.4.7 (Ubuntu)
X-Frame-Options:DENY

Like I said, everything works in a local development environment. How do I get this to work in deployment?

Daniel Ertel-Moore
  • 91
  • 1
  • 1
  • 12

0 Answers0