【发布时间】:2018-05-10 00:38:14
【问题描述】:
我在树莓派服务器上通过 localtunnel 托管了我的 rest 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});
我在我的 express 文件 app.js 中包含了 CORS 模块:
var cors = require("cors");
app.use(cors());
我在另一台服务器上的 rest 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 路由中?
【问题讨论】:
-
您是否收到错误消息?你的路线是什么样的?您需要确保为该问题发布足够的信息并包含minimal, complete, and verifiable example。
-
@LMulvey — 仅供参考:左方括号、mcve、右方括号 = minimal reproducible example
-
谢谢,@Quentin。我发帖后就抓到了。我不应该在早上喝咖啡之前回答问题。
-
@LMulvey 对不起,伙计们,我更新了 OP 以更清晰
标签: javascript node.js ajax cors axios