【问题标题】:Angular CLI, post request to a local API, returning nullAngular CLI,将请求发布到本地 API,返回 null
【发布时间】:2020-10-21 15:19:01
【问题描述】:

我以前问过这个问题,但我想我可能已经缩小了错误的可能性,所以我在更具体的同时再次问。

我正在尝试将此发布请求实现到 Angular 应用程序中的本地 API,但它只返回 null。 API 可以自行运行,大部分代码似乎都可以在我的应用程序中运行,但显然缺少一些使其无法运行的东西。

我的代码似乎成功调用了 api,因为如果我使用字符串而不是对象(API 所期望的)来测试它,我会在控制台中收到一条错误消息,在该控制台中我与 @ 并行启动了 API 987654322@

所以这是我提示用户输入字符串的代码,以及我将字符串转换为对象并尝试将其传递到我的发布请求的代码。

1/app.component.html

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Enter your String bellow:';
  result;

  constructor(private http: HttpClient) {}

    onSubmit(textEnter: string) {
      let json = {
      "string": textEnter
    };

      console.log(json);
      return this.http.post('http://localhost:3000/parentheses/', json).toPromise().then((data:any) => {
        console.log("testing");
        this.result = data.json;
      });
    }
}

2/app.components.ts

<div>
  <form>
     <input #textEnter placeholder="text">
     <button type="submit" (click)="onSubmit(textEnter.value)">click here</button>
  </form>

  <pre>
    {{ (result | async) | json }}
  </pre>

</div>

我还创建了一个proxy.config.json 文件:

{
  "/parentheses":{
    "target": "http://localhost:3000",
    "secure": false,
    "logLevel1": "debug"
  }
}

感谢您的帮助!

【问题讨论】:

  • 尝试删除异步管道,你不会返回一个可观察的。 {{result | json}}
  • 我的第一个猜测是查看 xss 问题。您正在发布到端口 3000,但我敢打赌您的应用程序是从不同的本地端口提供的,并且您正在通过 localhost:4321 或与端口 3000 不同的类似方式访问它
  • 无论哪种方式,该值最初是未定义的,您没有在模板中处理它。您应该键入您的属性,以便更清楚地知道发生了什么,并且编译器实际上可以帮助您。此外,组件通常不应该直接访问 HttpClient,我建议使用 observables。
  • 谢谢你们的帮助! @Sam,不,那没有用。事实上,它不再返回null,但什么也没有。 @Max我创建了一个代理文件,我在我的问题中添加了它。不应该这样做吗? @jonsharpe,好的,我将不得不调查一下,thatnks

标签: json angular api post angular-cli


【解决方案1】:

如下更改您的代码。在您的代码中,您在 html 代码中使用异步管道。但是“结果”变量不是可观察类型的变量。

    export class AppComponent {
          title = 'Enter your String bellow:';
          result: Observable<any>;
        
          constructor(private http: HttpClient) {}

          onSubmit(textEnter: string) {
              let json = { string: textEnter};
              this.result = this.http.post('http://localhost:3000/parentheses/', json);
          }
    }

像这样更改您的 HTML 代码。 但作为您的代码,它不需要返回 http 请求。

<pre>
   {{ result | json }}
</pre>

【讨论】:

  • 谢谢,这看起来很有希望。但不幸的是,它没有奏效。我仍然收到null
  • 其实我得到了这个:Type 'Promise&lt;Object&gt;' is missing the following properties from type 'Observable&lt;any&gt;': _isScalar, source, operator, lift, and 6 more. (property) AppComponent.result: Observable&lt;any&gt;
  • 您试图将承诺一保存到 Observable 类型变量。请确保不要使用“ .toPromise() ”。
  • this.result = this.http.post('localhost:3000/parentheses', json);
猜你喜欢
  • 2018-06-05
  • 2018-11-23
  • 2020-10-20
  • 1970-01-01
  • 2019-11-03
  • 2020-12-15
  • 1970-01-01
  • 2017-05-21
  • 2015-08-14
相关资源
最近更新 更多