[英]CORS middleware doesn't work in nodeJS
我在通过localtunnel托管的树莓派服务器上将我的其余api公开,并尝试从本地主机节点应用程序访问API。 本地节点应用程序在express上运行,并具有一些静态JS文件。 从一个静态JS文件中,我正在执行axios ajax请求以获取REST 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});
我在快递文件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路由中?
我是否应该不仅将CORS中间件包括在本地节点应用程序中,还应该包括在REST API路由中?
Excactly! Api端点需要打开电源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.