Responding with a JSON object in Node.js (converting object/array to JSON string)

前端 未结 6 1095
广开言路
广开言路 2020-12-04 08:01

I\'m a newb to back-end code and I\'m trying to create a function that will respond to me a JSON string. I currently have this from an example

function rando         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 08:33

    const http = require('http');
    const url = require('url');
    
    http.createServer((req,res)=>{
    
        const parseObj =  url.parse(req.url,true);
        const users = [{id:1,name:'soura'},{id:2,name:'soumya'}]
    
        if(parseObj.pathname == '/user-details' && req.method == "GET") {
            let Id = parseObj.query.id;
            let user_details = {};
            users.forEach((data,index)=>{
                if(data.id == Id){
                    user_details = data;
                }
            })
            res.writeHead(200,{'x-auth-token':'Auth Token'})
            res.write(JSON.stringify(user_details)) // Json to String Convert
            res.end();
        }
    }).listen(8000);
    

    I have used the above code in my existing project.

提交回复
热议问题