Sveltekit端点总是返回200个状态
我正在使用Sveltekit,并且有端点问题。我要发布到一个端点,即使具有400个身份,它也总是返回200个状态。
login.svelte
const res = await fetch('login', {
method: 'POST',
body: JSON.stringify({
email,
redirect: `${window.location.origin}/app/dashboard`
})
});
端点-Login.js
export const post = async ({request}) => {
console.log("Inside request");
return {
status: 400
};
}
通过控制台日志所看到的端点被击中,但状态在响应对象中返回200。
I am using SvelteKit and am having an issue with endpoints. I am posting to an endpoint and it's always returning a 200 status, even with a hardcoded 400 status.
Login.svelte
const res = await fetch('login', {
method: 'POST',
body: JSON.stringify({
email,
redirect: `${window.location.origin}/app/dashboard`
})
});
ENDPOINT - login.js
export const post = async ({request}) => {
console.log("Inside request");
return {
status: 400
};
}
The endpoint is being hit as seen through a console log, but the status is returned 200 in a Response object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是微妙的。但这最终很有意义。
如果我们阅读 docs> 。具体来说:
因为您使用的是页面端点,所以(而不是独立端点)Sveltekit有2条用于
POST /login < /code>的路由。一个返回html页面(
login.svelte
)的人,一个返回JSON(login.js
中定义的页面端点)。因此,我们需要做的是告诉服务器,我们期望在
application/json
而不是text/*
中期望结果(后者似乎是获取的默认值,这似乎是) 。这样,服务器知道要返回的路线。有2个解决方案:1。更新您的获取语句以包括
Accept
标题;或2:将您的登录名称重命名为也不是路由的东西,因此服务器不会感到困惑。我个人更喜欢第一个,因为它在技术上更正确。因此,您的
login.svelte
函数将成为:The problem is subtle. But it makes sense in the end.
If we read the docs carefully, we can figure out what's going on. Specifically:
Because you are using page endpoints, (rather than standalone endpoints) Sveltekit has 2 routes for
POST /login
. One that returns the HTML page (thelogin.svelte
), and one that returns the JSON (the page endpoint defined inlogin.js
).So what we need to do is tell the server that we are expecting the result in
application/json
rather thantext/*
(the latter is the default for fetch it seems). This way the server knows which route to return.There are 2 solutions to this: 1. Update your fetch statement to include the
accept
header; or 2: Rename your login.js to something that isn't also a route, so the server doesn't get confused what to return.I personally prefer the first one as it's technically more correct. So then your
login.svelte
function would become: