Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST Request to expressjs not working despite using CORS

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?

like image 281
MGS Avatar asked Dec 12 '17 21:12

MGS


1 Answers

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

like image 67
Faz Avatar answered Nov 15 '22 03:11

Faz