简体   繁体   English

如何在 sapper 上获得正确的 http 状态代码?

[英]How can i get right http status code on sapper?

I created register page, and submit without any input.我创建了注册页面,并在没有任何输入的情况下提交。 I got 200 ok though backend server raise 400 reseponsed how can i get right status on my js code?虽然后端服务器提高了 400 响应,但我得到了 200 确定,我怎样才能在我的 js 代码上获得正确的状态? 网站截图

200 ok 状态码

后端错误信息

below image is api call to my backend server and responsed 400 status下图是对我的后端服务器的 api 调用并响应了 400 状态

400 状态

api.js api.js

const base = 'https://gyma9z0wme.execute-api.ap-northeast-2.amazonaws.com/dev';
// const base = 'http://127.0.0.1:8000';

function send({ method, path, data, token }) {
    const fetch = process.browser ? window.fetch : require('node-fetch').default;

    const opts = { method, headers: {} };

    if (data) {
        opts.headers['Content-Type'] = 'application/json';
        opts.body = JSON.stringify(data);
    }

    if (token) {
        opts.headers['Authorization'] = `Bearer ${token}`;
    }

    return fetch(`${base}/${path}`, opts)
        .then(r => r.text())
        .then(json => {
            try {
                return JSON.parse(json);
            } catch (err) {
                return json;
            }
        });
}

export function get(path, token) {
    return send({ method: 'GET', path, token });
}

export function del(path, token) {
    return send({ method: 'DELETE', path, token });
}

export function post(path, data, token) {
    return send({ method: 'POST', path, data, token });
}

export function put(path, data, token) {
    return send({ method: 'PUT', path, data, token });
}

utils.js实用程序.js

export function post(endpoint, data) {
    return fetch(endpoint, {
        method: 'POST',
        credentials: 'include',
        body: JSON.stringify(data),
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(r => r.json());
}

auth/register.js身份验证/注册.js

import * as api from "api.js";

export function post(req, res) {
  const user = req.body;

  api.post("users", user).then(response => {
    if (response.user) {
      req.session.user = response;
    }

    res.setHeader("Content-Type", "application/json");

    res.end(JSON.stringify(response));
  });
}

register/index.svelte注册/索引.svelte

<script>
  import { goto, stores } from "@sapper/app";
  import ListErrors from "../_components/ListErrors.svelte";
  import { post } from "utils.js";
  const { session } = stores();
  let username = "";
  let email = "";
  let password = "";
  let errors = null;
  async function submit(event) {
    const response = await post(`auth/register`, { username, email, password });
    // TODO handle network errors
    if (response.status === 400){
      errors = response;
    }
    if (response.sn) {
      $session.sn = response.sn;
      goto("/");
    }
  }
</script>

<svelte:head>
  <title>회원가입 • Razberry</title>
</svelte:head>

<div class="auth-page">
  <div class="container page">
    <div class="row">
      <div class="col-md-6 offset-md-3 col-xs-12">
        <h1 class="text-xs-center">회원가입</h1>
        <p class="text-xs-center">
          <a href="/login">이미 회원인가요?</a>
        </p>

        <ListErrors {errors} />

        <form on:submit|preventDefault={submit}>
          <fieldset class="form-group">
            <input
              class="form-control form-control-lg"
              type="text"
              placeholder="Your Name"
              bind:value={username} />
          </fieldset>
          <fieldset class="form-group">
            <input
              class="form-control form-control-lg"
              type="text"
              placeholder="Email"
              bind:value={email} />
          </fieldset>
          <fieldset class="form-group">
            <input
              class="form-control form-control-lg"
              type="password"
              placeholder="Password"
              bind:value={password} />
          </fieldset>
          <button class="btn btn-lg btn-primary pull-xs-right">회원가입</button>
        </form>
      </div>
    </div>
  </div>
</div>

I'm using realworld code.我正在使用现实世界的代码。

https://github.com/sveltejs/realworld https://github.com/sveltejs/realworld

Try logging in with incorrect information by here.尝试在此处使用不正确的信息登录。 you can get same result你可以得到相同的结果

https://realworld.svelte.dev/login https://realworld.svelte.dev/login

Might be that the server responds the request with a 200 / OK via http, even if there is an error on backend side.可能是服务器通过 http 以 200 / OK 响应请求,即使后端出现错误。 Bad behavior for a backend, but real world...后端的不良行为,但现实世界......

On the other side you can add a .catch(()=>{}) statement to your fetch()ing function send in api.js to handle the error.另一方面,您可以在 api.js 中发送的 fetch()ing 函数中添加一个.catch(()=>{})语句来处理错误。

The response status is not part of the error.响应状态不是错误的一部分。 The status can be found in response.status as you expected.如您所料,状态可以在 response.status 中找到。 So the server responds with a 200/OK HTTP Status.因此服务器以 200/OK HTTP 状态响应。

Take a look at the response body.看一下响应体。 I know a backend wich responds with 200/ok and in the body is a string "an error occured" :P我知道一个后端以 200/ok 响应,并且在正文中是一个字符串“发生错误”:P

  api.post("users", user).then(response => {
if (response.user) {
  req.session.user = response;
}

res.setHeader("Content-Type", "application/json");

res.end(JSON.stringify(response));

After the req.session.user = response, you have no 'else' clause, so the code falls through to setHeader and sends the response.在 req.session.user = 响应之后,您没有“else”子句,因此代码会落入 setHeader 并发送响应。 What you need to do:你需要做什么:

  api.post("users", user).then(response => {
if (response.user) {
  req.session.user = response;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(response));
} else { res.sendStatus(403).end(); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM