如何处理UnhandledPromiseRejectionWarning? “ url”参数必须为字符串类型

时间:2020-04-23 05:35:01

标签: node.js promise

我的代码

var axios = require("axios");
var userDetails;

function initialize() {
    var options = {
        url: "https://api.github.com/users/narenaryan",
        headers: {
            'User-Agent': 'axios'
        }
    };
    return new Promise(function(resolve, reject) {
        axios.get(options, function(err, resp, body) {
            if (err) {
                reject(err);
            } else {
                resolve(JSON.parse(body));
            }
        })
    })

}

function main() {
    var initializePromise = initialize();
    initializePromise.then(function(result) {
        userDetails = result;
        console.log("Initialized user details");
        // Use user details from here
        console.log(userDetails)
    }, function(err) {
        console.log(err);
    })
}

main();

我知道了

(node:15582) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received an instance of Object

我不明白。我看了this SO个问题。我应该在代码中的哪个位置设置process.on?

我试图更改我的代码

function initialize() {
    var options = {
        url: "https://api.github.com/users/narenaryan",
        headers: {
            'User-Agent': 'axios'
        }
    };
    return new Promise(function(resolve, reject) {
        axios.get(options) 
        .then(()=> resolve(JSON.parse(body))
        .catch(err => console.error(err))
        )

反正同样的问题。

(node:17021) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received an instance of Object
    at validateString (internal/validators.js:120:11)
    at Url.parse (url.js:159:3)
    at Object.urlParse [as parse] (url.js:154:13)
    at dispatchHttpRequest (/home/miki/examples/prom1/node_modules/axios/lib/adapters/http.js:66:22)
    at new Promise (<anonymous>)
    at httpAdapter (/home/miki/examples/prom1/node_modules/axios/lib/adapters/http.js:21:10)
    at dispatchRequest (/home/miki/examples/prom1/node_modules/axios/lib/core/dispatchRequest.js:52:10)
(node:17021) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)

})

}

如何处理此问题?

1 个答案:

答案 0 :(得分:1)

看起来axios get函数的第一个参数应该是url字符串。

从选项对象中删除网址,然后尝试修改代码,如下所示:

....
const url = "https://api.github.com/users/narenaryan"

axios.get(url, options, function(err, resp, body) {
...