【问题标题】:How to POST data to a URL from NestJs code?如何从 NestJs 代码将数据发布到 URL?
【发布时间】:2021-11-03 04:23:48
【问题描述】:

我有一个带有用户名和密码的登录表单。我正在尝试使用 Nest Js 身份验证策略here 验证这些凭据。因此,在相应的 auth.service.ts 文件中,我使用“nativescript core modules http”向 OAuth URL 发出 POST 请求以验证凭据。但这不起作用:


        import { Injectable } from '@nestjs/common';
        import { request } from "tns-core-modules/http";

        const OAUTH_URL = 'url';

        @Injectable()
        export class AuthService {

        async validateUser(username: string, password: string): Promise<any> {

            let data = new FormData();
            data.set('client_id', 'sb-nestjs-app!t36258');
            data.set('client_secret', 'XrHuBRhyvuVNYNJNHlWLgcuBIyc=');
            data.set('username', username);
            data.set('password', password);
            data.set('grant_type', 'password');
            data.set('response_type', 'token');

            request({
                url: OAUTH_URL,
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Accept": "application/json;charset=utf8"
                },
                content: data
            }).then((response) => {
                console.log('response => ' + response + ' statuscode ' + response.statusCode);
                if (response.statusCode == 200) {
                    const token = response.content['access_token'];
                    //TODO:
                    // need to send scope also
                    return token;
                }
            }, (e) => {
                console.log('error' + e);
                return null;
            });

            return null;
        }
    }

当我在上述代码到位后运行“nest start”时,我收到错误:找不到模块“./http-request”

我不确定这里发生了什么,我尝试了“npm install http-request”它也没有工作。 基本上,我需要将凭据发布到 NestJs 中的 OAuth url。有什么指导吗?谢谢。

【问题讨论】:

  • 什么是tns-core-modules/http?这是您在组织中使用的自定义模块吗?你能打印完整的堆栈跟踪吗?您是否尝试过使用 NestJS 提供的 HttpService?

标签: post nestjs nestjs-passport


【解决方案1】:

试试HttpModule from NestJS。 你也可以从 npm 尝试request,但他们弃用了这个包。从我在他们的讨论中看到的,这个包仍然有效,但你不会得到它的支持,或者任何东西。这里有一些alternatives

我不确定您使用的是正确的 request npm 模块。我说的是:

import { request } from "tns-core-modules/http"

祝你好运!

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多