我最近handleFetch在 Sveltekit 中发现了这个钩子。现在我试图用它来拦截对我的后端的调用(用 Go 编写),但似乎不起作用(除非我错过了一些东西)。
文档内容如下:
此函数允许您修改(或替换)在服务器上运行的加载或操作函数内(或预渲染期间)发生的获取请求。
我有src\hooks.server.js:
/** @type {import('@sveltejs/kit').HandleFetch} */
export async function handleFetch({ request, fetch }) {
console.log("HERE IN --------> HANDLE FETCH HOOK")
return fetch(request);
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我只是想通过在终端上打印消息来确保调用挂钩。
我有一个load函数src\routes\records\+page.server.js:
export async function load() {
console.log("HERE IN LOAD")
// const records = await getAllRecords(1, 10);
const response = await fetch(`http://127.0.0.1:8080/api/v1/records?page=1&per_page=2`);
const records = await response.json();
console.log(await records);
return records;
}
Run Code Online (Sandbox Code Playgroud)
尽管我看到HERE IN LOAD消息和正在打印的响应,但我从未看到指示钩子被击中的消息。
我缺少什么?
谢谢
我正在使用fetch API来制作类似于以下代码段的跨域请求
window.fetch('http://data.test.wikibus.org/magazines', { method: 'get'})
.then(function(response) {
var linkHeader = response.headers.get('Link');
document.querySelector('#link-header').innerText = 'The Link header is: ' + linkHeader;
});Run Code Online (Sandbox Code Playgroud)
<span id="link-header"></span>Run Code Online (Sandbox Code Playgroud)
如您所见,虽然在响应中返回了Link标头(以及其他一些标头),但仍无法访问它.我认为这是一个CORS问题,因为在本地请求中所有标头都是可访问的.
这是设计的吗?有没有解决这个问题的方法?
我有护照设置使用谷歌策略,可以直接到/ auth /谷歌伟大.我目前拥有它,以便当您使用google身份验证oauth2登录时,我的端点将通过检查a进行身份验证req.user.当我刚刚访问浏览器中的端点时,这可以正常工作.如果我去/auth/google,然后/questions,我将能够提出要求.但是当我尝试从redux发出一个获取请求时,我会收到一条错误消息Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0.它出现是因为fetch API试图进入我的/questions端点,通过我的loggedIn中间件,然后不满足if (!req.user)并重新定向.有关如何使用PassportJS和passport-google-oauth2从Fetch API进行身份验证的任何想法?
该loggedIn函数:
function loggedIn(req, res, next) {
if (req.user) {
next();
} else {
res.redirect('/');
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的'GET'端点的代码.
router.get('/', loggedIn, (req, res) => {
const userId = req.user._id;
User.findById(userId, (err, user) => {
if (err) {
return res.status(400).json(err);
}
Question.findById(user.questions[0].questionId, (err, question) => {
if (err) {
return …Run Code Online (Sandbox Code Playgroud) 我正在为一个简单的react / redux应用程序建模auth层。在服务器端,我有一个基于devise_token_auth gem 的API 。
我fetch用来发布登录请求:
const JSON_HEADERS = new Headers({
'Content-Type': 'application/json'
});
export const postLogin = ({ email, password }) => fetch(
`${API_ROOT}/v1/auth/sign_in`, {
method: 'POST',
headers: JSON_HEADERS,
body: JSON.stringify({ email, password })
});
// postLogin({ email: 'test@test.it', password: 'whatever' });
Run Code Online (Sandbox Code Playgroud)
这行得通,我得到200响应以及所需的所有数据。我的问题是,信息在响应正文和标头之间划分。
我可以这样解析JSON主体:
postLogin({ 'test@test.it', password: 'whatever' })
.then(res => res.json())
.then(resJson => dispatch(myAction(resJson))
Run Code Online (Sandbox Code Playgroud)
但是,这样myAction就不会从标头中获取任何数据(在解析JSON时丢失)。
有没有办法从fetch请求中获取标头和正文?谢谢!
如下代码:
fetch('http://localhost:8080/root/1487171054127/k_query_bearer_token', {
mode: 'no-cors', credentials: 'include'
})
.then(function (response) {
return response.text();
})
.then(function (text) {
console.log('Request successful', text.length);
})
.catch(function (error) {
log('Request failed', error)
});
Run Code Online (Sandbox Code Playgroud)
输出:
Request successful 0
Run Code Online (Sandbox Code Playgroud)
如果我使用curl:
curl 'http://localhost:8080/root/1487171054127/k_query_bearer_token' \
-H 'Cookie: JSESSIONID=CviS9IK8pcsqADdP-m0MRXX_AvUqfzjJPwk1Yytf.ee16d0a01ad5'
Run Code Online (Sandbox Code Playgroud)
我得到一个文本形式的令牌(长度!= 0)。
如果我通过以下方式输出响应标头:
curl 'http://localhost:8080/root/1487171054127/k_query_bearer_token'
-H 'Cookie: JSESSIONID=CviS9IK8pcsqADdP-m0MRXX_AvUqfzjJPwk1Yytf.ee16d0a01ad5'
--head
Run Code Online (Sandbox Code Playgroud)
我得到:
HTTP/1.1 200 OK
Connection: keep-alive
X-Powered-By: Undertow/1
Server: JBoss-EAP/7
Content-Type: text/plain
Content-Length: 1730
Date: Wed, 15 Feb 2017 16:17:00 GMT
Run Code Online (Sandbox Code Playgroud)
为什么我无法通过提取获取任何文本?
我需要将我的JSON响应转换为对象,我该如何实现?
我的JSON回复:
[
{
"id":296,
"nama":"Appetizer"
},
{
"id":295,
"nama":"Bahan"
}
]
Run Code Online (Sandbox Code Playgroud) 我想了解两种get方法之间的区别,一种工作,另一种不是,但是我不明白为什么。
这不起作用:
fetch('https://glo3102lab4.herokuapp.com/fee958c0-c320-40d0-a750-218f2d7c1303/tasks', {
method: 'GET',
}).then(res => res.json)
.catch(error => {
console.error('Error:', error);
})
.then(response => {
console.log(response);
});
Run Code Online (Sandbox Code Playgroud)
然后返回:
ƒjson(){[本地代码]}
这很好用:
fetch('https://glo3102lab4.herokuapp.com/fee958c0-c320-40d0-a750-218f2d7c1303/tasks').then(function(response){
response.json().then(function(data) {
console.log(data);
});
}).catch(function(error) {
console.log('Fetch Error:', error);
});
Run Code Online (Sandbox Code Playgroud)
然后返回:
{tasks:Array(4)}任务:(4)[{…},{…},{…},{…}] 原型:对象
如果您想尝试一下:
fetch('https://glo3102lab4.herokuapp.com/fee958c0-c320-40d0-a750-218f2d7c1303/tasks', {
method: 'GET',
}).then(res => res.json)
.catch(error => {
console.error('Error:', error);
})
.then(response => {
console.log(response);
});
Run Code Online (Sandbox Code Playgroud)
我正在使用js fetch API从JSON检索数据。它工作正常(即使在IE 11中也是如此),除了在Edge 17中我得到302之外,响应标头是:
我的本地网站在Mac上,我正在使用BrowserSync通过192.168.100.X:3000进行访问,然后更新了PC主机文件,如下所示:
192.168.100.X http://local.mysite.com
Run Code Online (Sandbox Code Playgroud)
这是我的访存电话:
fetch('/fr/fil-actualites-json', { mode: 'cors' })
.then(
function(response) {
console.log('code :' +response.status);
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
// do some stuff
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助;)
我正在尝试使用Fetch API。从示例看来,GET请求需要then以某种方式解析响应。
目前我正在这样做
fetch(url)
.then(response => response.json())
.then(response => {
console.log(response);
});
Run Code Online (Sandbox Code Playgroud)
但是,这首先then看起来像样板。我试图避免它,例如:
fetch(url)
.then(response => {
console.log(response.json());
});
Run Code Online (Sandbox Code Playgroud)
但是,这记录了我的Promise状态待定resolved。
我阅读了有关该主题的其他问题,并阅读了一些有关Promise的信息,但我不知道是否有可能将其组合为一个then(如果这样-怎么做?)。
例如,这里的两个答案指出:
不需要使用多个“ .then”
和
没有充分的理由拥有两个.then()处理程序,因为每个处理程序中的代码都可以组合成单个.then()处理程序
但是我无法让那个例子真正起作用-我仍然有一个承诺:)
相反,这里被接受的答案解释了.then实际上对结果做了一些事情(提取了promise的回报),但是如果我能以某种方式自己做到这一点(response.json().then()或者说response.json().getVal()或者是double语法),我就无法理解then。
我正在为fetch-api创建一个类型安全的包装器,并且我注意到打字稿编译器将其归类为完全有效的代码:
function foo(response: Response): Promise<Bar> { //response received from a fetch() call
const json: Promise<any> = response.json();
return json; //Promise<any> can be returned as Promise<Bar>?
}
Run Code Online (Sandbox Code Playgroud)
为什么可以直接返回Promise<any>as Promise<Bar>?这不应该需要某种类型的断言吗?
fetch-api ×10
javascript ×6
cors ×2
json ×2
ajax ×1
es6-promise ×1
node.js ×1
passport.js ×1
promise ×1
redux ×1
response ×1
svelte ×1
svelte-3 ×1
sveltekit ×1
typescript ×1