首页 文章

通过JS文件中的ajax调用解决跨域问题以从express文件中检索数据[重复]

提问于
浏览
0

这个问题在这里已有答案:

我需要从我的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 name;

    var myQueryUrl = "http://localhost:10000/turtles";

    $.ajax({url: myQueryUrl, method: 'GET'}).done(function(response){

            name = response.data[0].name;

            $('.DTurtles').append($('<p>' + name + '</p>'));

    }); 

});

我尝试使用sendFile('index.html'),但我认为这不是我想要的 . 这样做会在主页上加载我的html(localhost:3000 /),但是我需要动态地从海龟对象(名称)中提取数据,然后在我的html上显示它 .

当我使用sendFile('index.html')时,加载页面localhost:3000时出现以下错误

TypeError: path must be absolute or specify root to res.sendFile
   at ServerResponse.sendFile (C:\Users\hen\Desktop\Camp\assignments\optionalNodeAssignment\node_modules\express\lib\response.js:404:11)
   at C:\Users\hen\Desktop\Camp\assignments\optionalNodeAssignment\server.js:29:8
   at Layer.handle [as handle_request] (C:\Users\hen\Desktop\Camp\assignments\optionalNodeAssignment\node_modules\express\lib\router\layer.js:95:5)
   at next (C:\Users\hen\Desktop\Camp\assignments\optionalNodeAssignment\node_modules\express\lib\router\route.js:131:13)
   at Route.dispatch (C:\Users\hen\Desktop\Camp\assignments\optionalNodeAssignment\node_modules\express\lib\router\route.js:112:3)
   at Layer.handle [as handle_request] (C:\Users\hen\Desktop\Camp\assignments\optionalNodeAssignment\node_modules\express\lib\router\layer.js:95:5)
   at C:\Users\hen\Desktop\Camp\assignments\optionalNodeAssignment\node_modules\express\lib\router\index.js:277:22
   at Function.process_params (C:\Users\hen\Desktop\Camp\assignments\optionalNodeAssignment\node_modules\express\lib\router\index.js:330:12)
   at next (C:\Users\hen\Desktop\Camp\assignments\optionalNodeAssignment\node_modules\express\lib\router\index.js:271:10)
   at expressInit (C:\Users\hen\Desktop\Camp\assignments\optionalNodeAssignment\node_modules\express\lib\middleware\init.js:33:5)

当我尝试res.send(turtles.data.name),然后单击我的html页面上的按钮来发出ajax请求并尝试显示名称时出现错误:

XMLHttpRequest cannot load http://localhost:10000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

AlainIb,建议我只返回整个乌龟对象而不仅仅是turtle.name . 他还建议我创建一个好的路径文件

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?这些解决方案中的任何一个都能解决我的跨域问

1 回答

  • 0

    您必须使用此语法来创建文件的良好路径

    app.get('/', function (req, res, next) {
       // path.join use the good separator accroding to your OS ( \ or / )
       res.sendFile(path.join(__dirname, '../', '../', 'client', 'index.html'));
    });
    

    例如,如果您有这样的文件夹:

    • /server/api/SERVERFS.JS

    • /client/index.html


    节点方面

    // return all the data array ( remove ".name" )
    app.get('/', function (req, res) {
          res.send(turtles.data);
    });
    

    角边

    function displayTurtles(){  
    
        var emptyArray = [];
    
        var myQueryUrl = "http://localhost:10000/";
    
        $.ajax({url: myQueryUrl, method: 'GET'}).done(function(response){
            // if you want all the data no need to iterate over it, just reference it
            emptyArray = response.data;    
            console.log("response:");
            console.log(emptyArray);
        });
        // this log will be empty because it will be loged before thath the server return the array data, don't forget ajax in asyncrhonus
        console.log("useless log":emptyArray);
        // if you need do to other thing with emptyArray call a function her   
        doStuff(emptyArray );
    }
    

    你应该在你的控制台中:console.log(“无用的日志”:...);然后是console.log(“response:”); ajax返回需要时间和调用后的行立即执行,它不等待响应

相关问题