使用异步/等待语法的nodejs http请求

时间:2018-11-18 17:01:37

标签: node.js http async-await

如何使用async / await语法发出http发布请求? 我需要一个http发布请求,而不使用旧样式的回调或promise, 我想将新的es6样式用于异步操作async / await。 而且我也不想使用任何第三方软件包。

const data = JSON.stringify({
    name: 'majid',
});

const options = {
    hostname: 'example.com',
    port: 443,
    path: '/api/v1/test',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'token': '32rt35y43t43t'
    }
};

try {
    const response = await https.request(options);

    console.log(response);

}
catch (error) {
    console.log(error);
}

我知道上面的语法,但是我不知道将请求内容放在哪里。 我正在使用nodejs 10.10。

我的问题被标记为重复,但是我检查了应该解决我的问题, 但没有运气,这个问题没有说关于后身的事情。

感谢@ jfriend00,我的问题已解决,这是我的代码:

import rp from 'request-promise';

exports.echoApi = async () => {

    const options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        uri: 'https://example.com/echo',
        body: {
            name: 'majid'
        },
        json: true
    };


    try {
        return await rp(options);
    }
    catch (error) {
        console.log(error);
    }

};

1 个答案:

答案 0 :(得分:-2)

await必须在async函数中使用。您可以执行在异步函数中编写的try / catch块:

async function myAsyncFn() {
    try {
        const response = await https.request(options);
        console.log(response);
    }
    catch (error) {
        console.log(error);
    }
}

请参阅有关MDN的文章:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await