node.js 创建服务器,后端本地接口返回数据

技术 · 2023-07-10
node.js 创建服务器,后端本地接口返回数据

后端app.js:

const express=require('express')
const app=express()
app.get('/test',function(req,res){
    res.setHeader('Access-Control-Allow-Origin','*') //跨域处理
    let data=[
        {id:0,name:'张三',age:23},
        {id:1,name:'李四',age:13},
        {id:2,name:'王五',age:42},
        {id:3,name:'刘能',age:55},
        {id:4,name:'赵四',age:34},
    ]
    let result={
        code:1,
        data
    }
    res.send(JSON.stringify(result))
})
app.listen(8000,function(){
    console.log('app is runing at http://127.0.0.1:8000/test')
})

前端html:

    <ul></ul>
    <button>发送请求</button>

js部分:

        let ul=document.querySelector('ul')
        let btn=document.querySelector('button')
        btn.addEventListener('click',function(){
            let xhr=new XMLHttpRequest()
            xhr.open('GET','http://127.0.0.1:8000/test')
            xhr.send()
            xhr.onreadystatechange=function(){
                if(xhr.readyState===4){
                    if(xhr.status === 200){
                        
                        let {data}=JSON.parse(xhr.response)
                        data.forEach(item => {
                            let li=document.createElement('li')
                            li.innerHTML='他的信息是'+item.name+'-'+item.age
                            //ul.appendChild(li)
                            ul.insertBefore(li,ul.children[0])
                        });
                    }
                }
            }
        })
node.js
  1. 铅笔 2023-07-12

    不错,继续加油~😄😄

Theme Jasmine by Kent Liao