简体   繁体   中英

Populate Data from API with Node.js

I run into the error: "write after end" while populating the user data from an API with Node.js. I used an async function to get the data and used await before I used the received data to write it into the document with the node server.

Thanks for your help!

const http = require('http');
const https = require('https');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    homeVerleitung(req, res);
    userVerleitung(req, res);
    res.end('Footer\n');
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

function homeVerleitung(request, response) {
    if (request.url === '/') {
        response.setHeader('Content-Type', 'text/plain');
        response.write('Header\n');
        response.write('Home\n');
    }
}

function userVerleitung(request, response) {
    if (request.url.length > 1) {
        response.setHeader('Content-Type', 'text/plain');
        const usedUrl = request.url.replace('/', '');
        response.write('Header\n');
        response.write(`${usedUrl}\n`);
        const asyncFunk = async (request, response) => {
            const userData = await getProfile(usedUrl);
            await response.write('Name of User is: ' + userData.name);
            await response.end('End');
        };
        asyncFunk(request, response);
    }
}

function getProfile(url) {
    return new Promise((resolve, reject) => {
        https
            .get(`https://teamtreehouse.com/${url}.json`, (res) => {
                let body = '';

                res.on('data', (d) => {
                    body += d.toString();
                });
                res.on('end', (d) => {
                    const jsonBody = JSON.parse(body);
                    resolve(jsonBody);
                });
            })
            .on('error', (e) => {
                console.error(e);
            });
    });
}

This is because you are calling response.end() twice. just remove the

res.end('Footer\n')

from the createServer function and add it to your homeVerleitung function:

function homeVerleitung(request, response) {
    if (request.url === '/') {
        response.setHeader('Content-Type', 'text/plain');
        response.write('Header\n');
        response.write('Home\n');
        response.end('Footer\n');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM