【问题标题】:How can I use Location header?如何使用 Location 标头?
【发布时间】:2021-11-12 23:25:42
【问题描述】:

我使用 Spring Boot 构建 REST API,并在 react 应用程序中使用此 API。

我想创建一个新资源(POST),并在创建后立即向该资源添加一个文件(PUT)。我不会在一个请求中这样做,因为我关注that answer

有POST请求:

fetch(`http://localhost:8080/authors`, {
            method: 'post',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                //body
            })
        }).then(r => console.log(r))

从服务器的角度来看,我这样处理这个 url:

//URL: http://localhost:8080/authors
@PostMapping
ResponseEntity<Author> createAuthor(@RequestBody Author author) {
    var result = repository.save(author); //JpaRepository
    return ResponseEntity.created(URI.create("/" + result.getAuthorId())).body(result);
}

所以我返回带有 Location 标头的响应。我的问题是:如何使用它向此标头指向的位置发送另一个请求? 正如您在上面看到的,我使用console.log 来查看服务器给我的响应。就是这样:

Response { type: "cors", url: "http://localhost:8080/authors", redirected: false, status: 201, ok: true, statusText: "", headers: Headers, body: ReadableStream, bodyUsed: false }
​
body: ReadableStream { locked: false }
​
bodyUsed: false
​
headers: Headers {  }
​​
   <prototype>: HeadersPrototype { append: append(), delete: delete(), get: get(), … }
​​​
   append: function append()
​​​
   constructor: function ()
​​​
   delete: function delete()
​​​
   entries: function entries()
​​​
   forEach: function forEach()
​​​
   get: function get()
  ​​​
   has: function has()
​​​
   keys: function keys()
​​​
   set: function set()
​​​
   values: function values()
​​​
   Symbol(Symbol.toStringTag): "Headers"
​​​
   Symbol(Symbol.iterator): function entries()
​​​
   <prototype>: Object { … }
​
ok: true
​
redirected: false
​
status: 201
​
statusText: ""
​
type: "cors"
​
url: "http://localhost:8080/authors"

没有关于Location标头的信息,所以我不知道如何使用它,因为响应中不包含它

【问题讨论】:

  • 获取获取响应:fetch(...).then(r =&gt; r.text()).then(url =&gt; { /* do stuff with url */ }) 编辑:如果你真的需要一个标题,你需要fetch(...).then(r =&gt; { /* read r.headers */ });
  • @ChrisG 我确实做到了,但没有我需要的“位置标头”
  • 您可以在浏览器的开发工具中检查服务器响应。按 F12 查看它们,然后切换到控制台选项卡并确保 xhr 已打开。运行请求并检查 URL 的结束位置。
  • 是的,使用xhr 我可以看到它,但是当我这样做时:console.log(r.headers.Location)` 我得到undefined
  • 基于后端代码,URL 似乎在正文中?您是否尝试了我第一条评论中的第一行代码?也可以试试r.headers.get("Location")。示例代码:jsfiddle.net/3phbzj8x

标签: javascript fetch location


【解决方案1】:

fetch 返回一个承诺,你可以使用 .then() 进行任何你想要的调用,它会是这样的:

    fetch(url, { method: 'POST', redirect: 'follow'})
.then(response => {
    // another call or anything you want to do
})
.catch(function(err) {
    console.info(err + " url: " + url);
});

【讨论】:

    猜你喜欢
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    相关资源
    最近更新 更多