跨域问题阻止我的ajax调用从我的快递文件中检索数据

我需要检索并显示来自我的node / exprss文件(app.js)的数据并将其显示在我的index.html中。 我在我的frontend.js文件中对localhost:3000 / turtles发出ajax请求,但这是我跨域问题的地方。

APP.JS文件

var express = require('express'); var app = express(); app.get('/turtles', function(req, res){ var turtles = { message: "success", data: [ { name: "Raphael", favFood: "Pizza" }, { name: "Leonardo", favFood: "Pizza" }, { name: "Donatello", favFood: "Pizza" }, { name: "Michelangelo", favFood: "Pizza" } ] }; res.send(turtles.data[0].name); }); app.listen(10000, function(){ console.log("Port is on 10000!"); }); 

FRONTEND.JS

  $(document).ready(function(){ var names = []; var turtles = []; var myQueryUrl = "http://localhost:10000/turtles"; $.ajax({url: myQueryUrl, method: 'GET'}).done(function(response){ names = response.data; turtles.push(response.data); console.log(names) console.log(turtles) $('.DTurtles').append($('<p>' + name + '</p>')); }); }); 

我尝试使用sendFile('index.html'),但我认为这不是我所期待的。 这样做会加载我的主页上的html(localhost:3000 /),但我需要从海龟对象(名称)dynamic拉动数据,然后显示在我的HTML。

AlainIb,build议我只返回整个turtle.data对象,而不仅仅是turtle.data.name。 他还build议我像这样创build一个好的path文件

 router.get('/', function (req, res, next) { res.sendFile(path.join(__dirname, '../', '../', 'client', 'index.html')); }); 

我有我的所有文件在同一目录中。 有人能解释一下上面的语法吗? 为什么它是router.get而不是app.get,特别解释这个部分

 res.sendFile(path.join(__dirname, '../', '../', 'client', 'index.html')); 

我也读过,我应该允许CORS做下面的事情

 app.all('/', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); app.get('/', function(req, res, next) { // Handle the get for this route }); app.post('/', function(req, res, next) { // Handle the post for this route }); 

但我不知道这一切是什么。 app.all函数中的下一个参数在哪里,什么是res.header? 这些解决scheme是否能解决我的跨域问题?

更新:我在我的获取处理函数中添加了下面的代码,假设返回的数据,我要求与ajax调用:

 app.get('/turtles', function(req, res, next){ res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); var turtles = { message: "success", data: [ { name: "Raphael", favFood: "Pizza" }, { name: "Leonardo", favFood: "Pizza" }, { name: "Donatello", favFood: "Pizza" }, { name: "Michelangelo", favFood: "Pizza" } ] }; res.send(turtles.data); }); 

我不再收到跨域问题的错误消息; 但是,在我的frontend.js中,当我console.log龟和名称,它显示为未定义,这意味着我没有回来的数据。 我怎样才能获得数据?

res.send(...)中的res.json(...)修改为res.json(...)