从服务器端到前端获取信息

时间:2020-05-31 06:45:57

标签: javascript node.js

我在后端node.js和前端使用常规js。我试图通过以下行从服务器发送信息:

res.status(200).send({ message: "Hello!" });

我在客户端尝试了一些代码。在下面的代码中,我没有收到消息。

var request = new XMLHttpRequest();

request.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        console.log(request);
    }
};

request.open('GET', 'http://localhost:3000/newUser');
request.send();

这是我在控制台中得到的:

XMLHttpRequest {readyState:4,超时:0,withCredentials:false,上载:XMLHttpRequestUpload,onreadystatechange:ƒ,…} onabort:null 错误:null onload:null onloadend:null onloadstart:null 进行中:null onreadystatechange:ƒ() 参数:null 来电者:空 长度:0 名称: ”” 原型:{构造函数:ƒ} 原始:ƒ() [[FunctionLocation]]:newUser.js:111 [[范围]]:范围[2] ontimeout:null readyState:4 回应: responseText:“ responseType:“” responseURL:“ http://localhost:3000/newUser” responseXML:空 状态:200 statusText:“确定” 超时:0 上传:XMLHttpRequestUpload {onloadstart:null,onprogress:null,onabort:null,onerror:null,下载:> null,…} withCredentials:假 原始:XMLHttpRequest

我也尝试过使用POST而不是GET,但是我没有从控制台得到任何信息。 还有其他方法可以将消息从服​​务器发送到我的客户端吗?

1 个答案:

答案 0 :(得分:0)

尝试使用此示例

fetch('http://dummy.restapiexample.com/api/v1/employees',{
    method:'GET'
}).then(response => response.json()).then((value)=>{
    console.log(value)
}).catch(error=>{
    console.log(error);
})