解决跨域问题以在JS文件中使用AJAX调用从Express文件中检索数据



我需要从我的node/exprss文件(app.js)检索并显示数据,然后在我的index.html上显示它。我向Localhost提出了Ajax请求:frontend.js文件中的3000/海龟,但这是我遇到跨域问题的地方。

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:UsershenDesktopCampassignmentsoptionalNodeAssignmentnode_modulesexpresslibresponse.js:404:11)
   at C:UsershenDesktopCampassignmentsoptionalNodeAssignmentserver.js:29:8
   at Layer.handle [as handle_request] (C:UsershenDesktopCampassignmentsoptionalNodeAssignmentnode_modulesexpresslibrouterlayer.js:95:5)
   at next (C:UsershenDesktopCampassignmentsoptionalNodeAssignmentnode_modulesexpresslibrouterroute.js:131:13)
   at Route.dispatch (C:UsershenDesktopCampassignmentsoptionalNodeAssignmentnode_modulesexpresslibrouterroute.js:112:3)
   at Layer.handle [as handle_request] (C:UsershenDesktopCampassignmentsoptionalNodeAssignmentnode_modulesexpresslibrouterlayer.js:95:5)
   at C:UsershenDesktopCampassignmentsoptionalNodeAssignmentnode_modulesexpresslibrouterindex.js:277:22
   at Function.process_params (C:UsershenDesktopCampassignmentsoptionalNodeAssignmentnode_modulesexpresslibrouterindex.js:330:12)
   at next (C:UsershenDesktopCampassignmentsoptionalNodeAssignmentnode_modulesexpresslibrouterindex.js:271:10)
   at expressInit (C:UsershenDesktopCampassignmentsoptionalNodeAssignmentnode_modulesexpresslibmiddlewareinit.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,建议我只是返回整个乌龟物体,而不仅仅是乌龟。他还建议我创建一个很好的路径文件,例如

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

我将所有文件都在同一目录中。有人可以解释上述语法的作用吗?为什么是路由器。

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中的下一个参数来自哪里,所有函数都来自什么,什么是res.header?这些解决方案中的任何一个都可以解决我的跨域问题吗?

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

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("响应:");AJAX返回花费时间,并立即执行通话后的线,它不会等待响应

相关内容

  • 没有找到相关文章

最新更新