Limpuls
Limpuls

Reputation: 876

CORS middleware doesn't work in nodeJS

I have my rest api on raspberry pi server hosted via localtunnel to public and trying to access the API from localhost node application. Local node application is running on express and have some static JS files. From one of the static JS files, I'm doing axios ajax request to rest api but getting CORS error to console:

script.js

 setTimeout(() => {
  axios.get('https://wvoegmuism.localtunnel.me/api/ninjas')
    .then(function (question) {
      var data = question.data;

  const questions = [];
  $.each(data, function(index, value) {
    console.log(JSON.stringify(value.the_question, null, "\t"))
    console.log(JSON.stringify(value.the_answer, null, "\t"))
    console.log(JSON.stringify(value.the_choices, null, "\t"))
    questions.push(new Question(value.the_question, value.the_choices, value.the_answer))




    //console.log(data[index].the_question);

  })
  quiz = new Quiz(questions)
  populate()
}), 1000});

I include CORS module to my express file app.js:

var cors = require("cors");
app.use(cors());

My rest api route file on another server to the endpoint:

var express = require("express");
var app = express();
var router = express.Router();
var mongoose = require("mongoose");
var customerschema = require("../models/customersSchema");
var jwt    = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('../config'); // get our config file
var user = require("../models/user");
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.set('superSecret', "tokenproject"); // secret variable
mongoose.Promise = require('bluebird');


router.get('/ninjas', function(req, res) {
  customerschema.find({}).then(function(ninjas) {
    res.send(ninjas);
  })
});

console error:

Failed to load https://wvoegmuism.localtunnel.me/api/ninjas: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

When following tutorial, it works for a guy, but not me. What I'm missing here? Should I include CORS middleware not only to my local node app but also to REST API routes?

Upvotes: 0

Views: 1048

Answers (1)

Thomas
Thomas

Reputation: 2536

Should I include CORS middleware not only to my local node app but also to REST API routes?

Excactly! The Api-Endpoint needs to turn cors on.

Upvotes: 1

Related Questions