微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用node做服务端,前端用Ajax获取服务端数据

1.首先要让node做服务端需要在项目中用express包

npm i express --save

然后建立一个server.js文件

//引入express
const express=require('express');
//创建应用对象
const app=express();
///创建路由规则
app.get('/server',(request,response)=>{
    //设置响应头,设置允许跨域
    response.setHeader('Access-Control-Allow-Origin',"*");
    response.send("hello ajax")
})
app.listen(8000,()=>{
    console.log("服务已启动,8000端口监听中....")
})

然后用node启动服务
用node启动服务之后,前端就能通过Ajax得方式获取后端得数据了

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <Meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #res
        {
            width: 100px;
            height: 100px;
            border: 1px solid aqua;
        }
    </style>
</head>
<body>
    <button>发送请求</button>
    <div id="res"></div>
</body>
<script>
    const btn=document.getElementsByTagName('button')[0];
    const res=document.getElementById("res")
    //发送请求
    btn.onclick=function(){
        const xhr=new XMLHttpRequest()
        const url='http://localhost:8000/server'
        xhr.open('GET',url)
        xhr.onreadystatechange=function(){
            
            if(xhr.readyState===4)
            { //4表示服务端返回了所有结果
           
                if(xhr.status>=200&&xhr.status<300)
                {
                //2开头得都表示成功
               
                //1.响应行
                console.log(xhr.status);//包括协议版本和状态码等信息
                //2.响应头
                console.log(xhr.getAllResponseHeaders());
                //3.响应体
                console.log(xhr.response);
                res.innerHTML=xhr.response;

                }
            }
        }
        xhr.send()
    }
</script>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐