这是因为在XHR.send()方法中传递的参数需要使用JSON.stringify()方法将其转换为字符串格式,否则XHR对象会将其默认转换为FormData格式,从而导致服务器无法正确解析请求。修改代码如下:

function downloadSong(id) {
    var XHR = new XMLHttpRequest();
    XHR.addEventListener('load', function(event) {
        alert('耶!已发送数据并加载响应。');
    });
    XHR.addEventListener('error', function(event) {
        alert('哎呀!出问题了。');
    });
    XHR.open('POST', 'https://daga.cc/yue/');
    XHR.setRequestHeader('origin', 'https://daga.cc');
    XHR.setRequestHeader('Content-Type', 'application/json');
    XHR.send(JSON.stringify({
        input: id,
        filter: 'id',
        type: 'netease',
        page: '1'
    }));
}
downloadSong(492228208);

通过设置请求头Content-Type为application/json,将请求体转换为JSON格式字符串,就可以正确地向服务器发送请求并获取JSON数据了。

JavaScript 使用 XMLHttpRequest 发送 JSON 数据到服务器

原文地址: https://www.cveoy.top/t/topic/oIp0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录