簡體   English   中英

Angular HttpClient 在正文中使用 JSON 發出 GET 請求

[英]Angular HttpClient make GET request with JSON in the body

我正在開發一個 Angular 客戶端應用程序和一個 ASP.NET Core Web API 后端,我在嘗試從 Angular 調用工作時遇到了一個問題,而 Postman 似乎可以正常工作。

打字稿代碼:

 exportScript(commands: ScriptCommand[]) {
    this.http.post(this.baseUrl + 'api/ScriptCommands/GenerateScript', JSON.stringify(this.scriptCommands)).subscribe();
  }

C# API 調用:

    [HttpGet]
    [Route("api/ScriptCommands/GenerateScript")]
    public IActionResult GenerateScript([FromBody]List<ScriptCommandViewModel> commands)
    {
        var mappedCommands = MapCommands(commands);
        var stream = ProcessCommands(mappedCommands);
        return File(stream, "application/xml", "generatedScript.xml");
    }

當我使用 Angular 調用時,我收到了 400 Bad Request,但如果我將 JSON 字符串化的 scriptCommand 列表復制到 Postman 請求的正文中,它就可以正常工作。

謝謝大家的幫助!

更新:更改了 Typescript 代碼 - 我仍然收到 HTTP 400 錯誤請求響應,但 Chrome 中的網絡選項卡在請求標頭中顯示了這一點 - 內容類型是“文本/純文本”問題嗎?

Accept: application/json, text/plain, */*
Content-Type: text/plain
Origin: http://localhost:4200
Referer: http://localhost:4200/createScript
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36

嘗試使用標題中的內容類型進行測試

'Content-Type': 'application/json'

'Content-Type': 'application/json;charset=utf-8'

通過在請求 url 中附加請求發送數據來獲取請求發送數據,因此如果您有一個像 {"page":1,"search":"new products"} 這樣的 json 正文。 要在獲取請求中發送此數據,您可以使用以下代碼。

get(path: string, params: any) {
    return this._http.get(this._baseUrl + path, { params: params })
      .pipe(timeout(CONST.API_TIMEOUT));
  }

這將像創建請求 url 一樣(可以在網絡選項卡的控制台中驗證)

http://localhost:5003/api/auth/test?page=1&search=new products

我認為 .append 的工作方式與我們想象的有點不同。 Append 返回附加的 HttpParams。 嘗試這個:

 exportScript(commands: ScriptCommand[]) {
    let httpParams = new HttpParams();
    httpParams  = httpParams.append("commands", JSON.stringify(this.scriptCommands));
    this.http.get(this.baseUrl + 'api/ScriptCommands/GenerateScript', { params: httpParams }).subscribe();
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM