2017-11-26 22 views
0

localbunnel을 통해 공개되고 localhost 노드 응용 프로그램에서 API에 액세스하려고하는 raspberry pi 서버에 내 휴식 API가 있습니다. 로컬 노드 응용 프로그램은 명시 적으로 실행 중이며 일부 정적 JS 파일이 있습니다. 정적 JS 파일 중 하나에서, 내가 콘솔에 API를하지만 점점 CORS 오류를 휴식 Axios의 아약스 요청하고 있어요 :CORS 미들웨어가 nodeJS에서 작동하지 않습니다.

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

내 특급 파일 app.js에 CORS 모듈을 포함 :

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

: 엔드 포인트에 다른 서버에

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

내 나머지 API를 루트 파일 콘솔 오류 :

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. 

튜토리얼을 따라 할 때, 그것은 튜토리얼을 따르는 경우 나에게 해당되는 것이지만 나에게는 해당되지 않습니다. 여기서 내가 놓친 게 뭐야? 로컬 노드 앱뿐만 아니라 REST API 경로에도 CORS 미들웨어를 포함시켜야합니까?

+1

오류가 있습니까? 당신의 경로는 어떻게 생겼습니까? 질문에 대한 충분한 정보를 게시하고 [최소한의 완전하고 검증 가능한 예] (https://stackoverflow.com/help/mcve)를 포함시켜야합니다. – LMulvey

+0

@LMulvey - FYI : 열린 대괄호, mcve, 닫는 대괄호 = [mcve] – Quentin

+0

고맙습니다, @Quentin. 내가 게시 한 직후에 잡았습니다. 아침 커피 전에 질문에 대답해서는 안됩니다. – LMulvey

답변

1

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

excactly! Api-Endpoint는 cors를 켜야합니다.

+0

예, 그랬습니다! 나머지 및 로컬 노드 서버를 다시 시작할 때까지 작동하지 않았습니다. 둘 다 nodemon을 실행 중이지만이 경우에는 수동 다시 시작이 필요합니다. 그것도 내 삶의 15 분처럼 낭비했다. 감사! – Limpuls