簡體   English   中英

AJAX對node.js服務器路由的調用-提供跨源請求錯誤

[英]AJAX post call to node.js server route - providing Cross origin request error

我是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庫-我將在整個問題下方提供代碼(也許存在node 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();
  }
}

將協議添加到您的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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM