CORS中间件在nodeJS中不起作用

时间:2017-11-26 18:40:13

标签: javascript node.js ajax cors axios

我将通过localtunnel托管的raspberry pi服务器上的其余api公开,并尝试从localhost节点应用程序访问API。本地节点应用程序在express上运行并具有一些静态JS文件。从其中一个静态JS文件,我正在做axios ajax请求来休息api但是把CORS错误带到控制台:

的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});

我将CORS模块包含在我的快递文件app.js中:

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

我在其他服务器上的api路由文件到端点:

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);
  })
});

控制台错误:

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.

当关注教程时,它适用于一个人,但不适合我。我在这里缺少什么?我是否应该将CORS中间件不仅包括在本地节点应用程序中,还包括REST API路由?

1 个答案:

答案 0 :(得分:1)

  

我是否应该将CORS中间件不仅包括在本地节点应用程序中,而且还包括   还有REST API路由吗?

Excactly! Api-Endpoint需要打开角色。