基于承诺的XHR返回未定义-JS

时间:2019-03-03 23:47:38

标签: javascript node.js xmlhttprequest

我正在node.js中构建一个Web服务器,并调用我的API来获取数据。我想通过创建XHR函数(名称为AJAX)来整理代码,并在每条路径中对其进行调用。我知道这个问题已经提出了多个版本,但是即使按照所有这些教程进行操作,我也无法得到答复。

XHR功能:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

exports.request = obj => {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.open(obj.method || "GET", obj.url);
        if (obj.headers) {
            Object.keys(obj.headers).forEach(key => {
                xhr.setRequestHeader(key, obj.headers[key]);
            });
        }
        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                console.log(xhr.response);
                resolve(xhr.response);
            } else {
                console.log(xhr.statusText)
                reject(xhr.statusText);
            }
        };
        xhr.onerror = () => reject(xhr.statusText);
        xhr.send(obj.body);
    });
};

我怎么称呼它:

const AJAX = require('../ajax');

// G1: GET All Clubs
exports.get_all_clubs = (req, res, next) => {
    console.log('Return all Clubs:')
    AJAX.request({
            url: "http://localhost:3000/clubs",
            method: "GET"
        })
        .then(data => {
            // Log out Data
            console.log(JSON.parse(data));
        })
        .catch(error => {
            console.log(error);
        });
}

我得到的答复是:

GET /clubs - - ms - -
Return all Clubs:
undefined
SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at AJAX.request.then.data (C:\Users\tyler\Desktop\Code\clubadmin\api\controllers\clubs.js:14:30)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)

该API正在运行,如果我在POSTMAN中测试了相同的路由,则会给出正确的响应。

0 个答案:

没有答案