Node.js请求库的相对uri [英] Relative uri for node.js request library

查看:95
本文介绍了Node.js请求库的相对uri的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,而node.js无法解析网址:

I have the following code, and node.js can't resolve the url:

const request = require('request')
const teamURL = `/users/${user._id}/teams`;

const req = request({
    url: teamURL,
    json: true
 }, 
 function(error, response, body) {

    if (!error && response.statusCode == '200') {

        res.render('userHome.html', {
            user: user,
            teams: body
        });
    } 
    else {
        console.error(error);
        next(error);
    }
});

在服务器端的node.js Express应用程序上,是否有一种很好的方法将相对路径/URL与请求库一起使用?

is there a good way to use relative paths/urls with the request library on a server-side node.js Express app?

推荐答案

仅提供一个相对的URL,如果从上下文中可以清楚知道该URL的根部分应该是有效的.例如,如果您在stackoverflow.com上并找到链接/questions,则从上下文中可以明显看出,完整的URL应该为stackoverflow.com/questions.

Giving just a relative url only works if it is clear from context what the root part of the url should be. For instance, if you are on stackoverflow.com and find a link /questions, it's clear from context the full url should be stackoverflow.com/questions.

请求库没有可用的此类上下文信息,因此它需要您提供完整的URL才能发出请求.您当然可以自己构建完整的url,例如,使用url.resolve():

The request library doesn't have this kind of context information available, so it needs the full url from you to do be able to make the request. You can build the full url yourself of course, for instance by using url.resolve():

var url = require('url');
var fullUrl = url.resolve('http://somesite.com', '/users/15/teams');
console.log(fullUrl); //=> 'http://somesite.com/users/15/teams');

但是,当然,这仍然需要您知道url的根部分.

But of course this will still require you to know the root part of the url.

这篇关于Node.js请求库的相对uri的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆