简体   繁体   中英

Await/async function in node js

I'm new to node js and I want to use the await statment to make my code waiting for a Promise. My promise is the use of Discord API to know if the user is a member of a specific server. But i got a error when execute "SyntaxError: await is only valid in async function". But my code is a async function, so i dont get what is wrong. Thank you.

(async () => {

const http = require('http');
const fs = require('fs');
const port = 53134;
const url = require('url');
const fetch = require('node-fetch');
const { execFile } = require('child_process');


let discordLog = async (accessCode) => {
    let isEclaire = false;
    const data = {
        client_id: '805884181811822624',
        client_secret: 'JRSPE0nmRn881Mi9cLC-gMozHKWLQVPT',
        grant_type: 'authorization_code',
        redirect_uri: 'http://localhost:53134',
        code: accessCode,
        scope: 'identify guilds',
    };
    return new Promise(() =>{
    fetch('https://discord.com/api/oauth2/token', {
        method: 'POST',
        body: new URLSearchParams(data),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
    })
    .then(discordRes => discordRes.json())
    .then(discordData => {
        console.log(discordData);
        return discordData;
    })
    .then(discordData => fetch('https://discord.com/api/users/@me', {
        headers: {
        authorization: `${discordData.token_type} ${discordData.access_token}`,
        },
    }))
    .then(userRes => userRes.json())
    .then(userData => {
        console.log(userData);
        return userData;
    })
    .then(userData => fetch(`https://discord.com/api/guilds/799385448824438824/members/${userData.id}`, {
        headers: {
        authorization: `Bot ODA1ODg0MTgxODExODIyNjI0.YBhYIQ.h4zLzR7ybBC1uvFSb4iZTH-JVhM`,
        },
    }))
    .then(guildRes => guildRes.json())
    .then(guildData => {
        console.log(guildData)
        for(let i = 0; i<guildData.roles.length; i++) {
            console.log(guildData.roles[i]);
            if(guildData.roles[i] == '786007786500784138' || guildData.roles[i] == '805560066715025468' ) isEclaire = true;
        }
        return(isEclaire);
        
        })
    })
}

http.createServer((req, res) => {
    let responseCode = 404;
    let content = '404 Error';
    const urlObj = url.parse(req.url, true);
    let isEclaire = false;

    if (urlObj.query.code) {
        const accessCode = urlObj.query.code;
    console.log(`The access code is: ${accessCode}`);
        isEclaire = await discordLog(accessCode);
        } 
  if(isEclaire){
        res.writeHead(301,{Location: 'https://www.speedtest.net/'});
    }else{
  if (urlObj.pathname === '/') {
    responseCode = 200;
    content = fs.readFileSync('./sso-discord.html');
  }
    res.writeHead(responseCode, {
        'content-type': 'text/html;charset=utf-8',
    },
    );
    res.write(content);
    }
    res.end();
})
.listen(port);
})()

Firstly createServer is not an async function. You should need to wrap the data fetching into a separate async function. and Then call it here.

Try making your http server's request event handler into an async function

Change this

 http.createServer((req, res) => {   /* not async */

to this

 http.createServer(async (req, res) => {

and be sure you're using a relatively recent version of nodejs.

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