6
votes

I've got this function in my component, that's supposed to send a POST request to an express API:

onSubmit (evt) {

      evt.preventDefault();
      //alert(JSON.stringify(this.description));
      axios.post('http://localhost:3000/api/v1/addComment', {
        articleid: this.id,
        description: this.description
      });

    }

This is the API to which the request is being sent:

router.post('/api/v1/addComment/', function(req, res){ 
  var newComment = req.body;
  //newComment.id = parseInt(commentsData.length);
  commentsData.comments.push(newComment);
    
  
  fs.writeFile('app/data/comments.json', JSON.stringify(commentsData), 'utf8', function(err){
       console.log(err);
  });
  
  res.setHeader("Access-Control-Allow-Origin", "*");  
  res.json(newComment);
});

I've also required the the neccessary CORS dependency in my express, app.js file

var express = require('express');
var reload = require('reload');
var app = express();
var cors = require('cors');
var dataFile = require('./data/articles.json');

app.set('port', process.env.PORT || 3000 );
//app.set('appData', dataFile);
app.set('view engine', 'ejs');
app.set('views', 'app/views');

app.use(express.static('app/public'));
app.use(require('./routes/index'));
app.use(require('./routes/comments'));
app.use(cors());

var server = app.listen(app.get('port'), function(){
  console.log('Listening on port ' + app.get('port'));
});

reload(server, app);

The API routes work fine, when I do get requests, however, I keep getting this error when I do a post request:

Failed to load http://localhost:3000/api/v1/addComment: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. createError.js?16d0:16 Uncaught (in promise) Error: Network Error at createError (createError.js?16d0:16) at XMLHttpRequest.handleError (xhr.js?ec6c:87)

I've also tried sending a headers object along with the axios post request, but to no avail. Based on my research into CORS, I understand that Using CORS is neccessary to allow requests to your API, coming from a different domain. My express server runs on localhost 3000, while my vue server runs at local host 8080.

Could someone explain why I'm still getting this error despite requiring and using CORS in express?

2

2 Answers

7
votes

Try moving the app.use(cors()) up before you assign the routes

0
votes

The pre-flight part is referring to xhr making a OPTIONS request to /api/v1/addComment before the actual POST. You'll need to configure cors to handle that:

// preflight for aspecific route
router.options('/api/v1/addComment/', cors())

// or preflight for all routes
router.options('*', cors())

Note: you'll want to make these calls before defining the rest of the routes. See the docs on npmjs.