【问题标题】:AJAX post call to node.js server route - providing Cross origin request errorAJAX post call to node.js server route - 提供跨源请求错误
【发布时间】:2015-10-09 01:48:09
【问题描述】:

我是 node.js 的新手,正在尝试使用我的基本 API 并在我的路由文件中调用正确的 router.get 函数。

我有一个用于 ajax 帖子的基本客户端 javascript:

console.log("main.js loaded");

var form = document.getElementById('addUserForm');
form.addEventListener("submit", function(event){
  event.preventDefault();
  var username = document.getElementById('username').value;
  var fd = new FormData();
  fd.append('username', username);

  window.ajaxCall.call("POST", "localhost:3000/api/users/add", fd, function(responseText){
    // var response = JSON.parse(responseText);
    console.log(response);
  });
});

在这个客户端 javascript 中,我使用的是自定义 xmlhttprequest 库 - 我将在整个问题下方提供代码(可能存在节点 js 的错误)

** 更新 ** 当我将 ajax 调用 url 更改为:/api/users/add 或 http://localhost:3000/api/users/add 我收到以下错误:POST http://localhost:3000/api/users/add 404 (Not Found)

这是我的路线文件:

var express = require('express');
var router = express.Router();


/* GET home page. */
router.get('/users', function(req, res) {
    var Users = require('../models/users'); // inkludiert das Users model
    var data; // undefined data variable

    Users.getData(function(err, result) { // ruft die getData Funktion vom Users Model auf
        // TODO: Error handling.
        data = result;
        render(data); // ruft die render Funktion auf und übergibt das Resultobjekt
    });

    function render(data){
      res.send(data);
    }
});

router.get('/api/users/add', function(req, res){
    console.log(req,res);
});

module.exports = router;

我要做的就是调用router.get('api/users/add'... 函数以继续使用我的api。

现在,当我尝试使用客户端 javascript ajax 调用执行此操作时,出现以下错误:

XMLHttpRequest cannot load localhost:3000/api/users/add. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

当我检查错误时,它显示错误发生在 js 文件中的 window.ajax 调用以及库中的回调函数中。

这是必要的库代码:

window.ajaxCall = {
  call: function(RequestType, pathToFile, data, cb){
    var ajax = null;
    if(window.XMLHttpRequest){ //Google Chrome, Mozilla Firefox, Opera, Safari,...
        ajax = new XMLHttpRequest();
    }else if(window.ActiveXObject){ // Internet Explorer
        try{
            ajax = new ActiveXObject("Msxml2.XMLHTTP.6.0");
        } catch(e){
            try{
                ajax = new ActiveXObject("Msxml2.XMLHTTP.3.0");
            }
            catch(e){}
        }
    }
    if(ajax!=null){
      ajax.open(RequestType, pathToFile, true);
      typeof data == "string" || typeof data == "array" ? ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded") : "" ;
      ajax.onreadystatechange = function() {
        if (ajax.readyState == 4) {
          if(this.status == 200){
            cb(ajax.responseText);
          }
        }
      }
      ajax.send(data);
    }
  },
  abort: function(){
    ajax.abort();
  }
}

【问题讨论】:

  • 而且协议、域和端口都一样吗?如,该网站是否也在 localhost 的 3000 端口上运行?
  • 您似乎缺少协议http://localhost
  • 是的,两者都在:3000。我不明白的是,如果我将我的 ajax 调用表单 localhost:3000/api/users/add 更改为 localhost:3000/api/users/add 我收到以下错误 POST localhost:3000/api/users/add 404 (Not Found)
  • 我已经更新了我的问题

标签: javascript ajax node.js xmlhttprequest


【解决方案1】:

将协议添加到您的 ajax 调用中。

window.ajaxCall.call("POST", "http://localhost:3000/api/users/add", fd, function(responseText){
    // var response = JSON.parse(responseText);
    console.log(response);
});

现在,对于 404 部分,您的路线期待获得,但您正在发送帖子,请按如下方式更改路由器:

router.post('/api/users/add', function(req, res){
    console.log(req,res);
});

【讨论】:

  • 您好,感谢您的意见。当我更改 ajax 调用 url 时,我已经用结果更新了我的问题。
  • 嗯,你现在得到的 404 是一个不同的错误,这似乎意味着现在你的请求正在到达你的服务器,但服务器无法解析路由。
  • 是的,我知道 - 但 router.get('/api/users/add', catch the request on that url ?
  • 不,不应该,检查我的编辑。路由器正在等待获取,您正在发送一个帖子。
  • 哦,拍摄 - 我在我的 ajax 中使用 post 并监听 get。不幸的是,在将其更改为您的代码后,我仍然得到相同的 404 ...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-31
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 2017-01-06
相关资源
最近更新 更多