使用标题获取 [英] Fetch with headers

查看:8
本文介绍了使用标题获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 fetch 在服务器中使用标头返回请求时

When use fetch for request in server using headers return

SyntaxError: Unexpected end of input
    at index.js:50
    at <anonymous>

第 50 行代码是 }).then(res => res.json())

Line of code 50 is }).then(res => res.json())

有什么问题?

获取此代码.

fetch(api-url, {
          mode: 'no-cors',
          method: "POST",
          headers: {
              'Accept': 'application/json',
                        'Content-Type': ' application/json',
                        'X-API-SERVER': '85499f9f'
                    },
        }).then(res => res.json())
          .then(res => {
            if (res.status === 200){
              console.log("accepted");
            }else {
              console.log(res.error);
            }

             console.log(res.error)
          }).catch(err => console.log(err))

推荐答案

由于您正在请求 API,因此您不想禁用 CORS.只要您的 API 服务器也发送正确的标头(>访问控制允许来源).

Since you're requesting an API, you don't want to disable CORS. It's probably enough to just remove mode: 'no-cors' in your fetch request to fix this, as long as your API server sends the correct headers as well (Access-Control-Allow-Origin).

这篇关于使用标题获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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