javascript MirageJs不会抛出状态400

dly7yett  于 2023-08-02  发布在  Java
关注(0)|答案(4)|浏览(91)

我是新的React,我正在使用useEffect进行React提取。我使用miragejs来模拟一个API服务器。我正在测试sad路径,并使miragejs API返回400状态码。
我使用miragejs来模拟一个API服务器。
这里是server.js

import { createServer, Model } from "miragejs"

createServer({
models: {
    vans: Model,
},

seeds(server) {
    server.create("van", { id: "1", name: "Modest Explorer", price: 60, description: "The Modest Explorer is a van designed to get you out of the house and into nature. This beauty is equipped with solar panels, a composting toilet, a water tank and kitchenette. The idea is that you can pack up your home and escape for a weekend or even longer!", imageUrl: "https://assets.scrimba.com/advanced-react/react-router/modest-explorer.png", type: "simple", hostId: "123" })
    server.create("van", { id: "2", name: "Beach Bum", price: 80, description: "Beach Bum is a van inspired by surfers and travelers. It was created to be a portable home away from home, but with some cool features in it you won't find in an ordinary camper.", imageUrl: "https://assets.scrimba.com/advanced-react/react-router/beach-bum.png", type: "rugged", hostId: "123" })
    server.create("van", { id: "3", name: "Reliable Red", price: 100, description: "Reliable Red is a van that was made for travelling. The inside is comfortable and cozy, with plenty of space to stretch out in. There's a small kitchen, so you can cook if you need to. You'll feel like home as soon as you step out of it.", imageUrl: "https://assets.scrimba.com/advanced-react/react-router/reliable-red.png", type: "luxury", hostId: "456" })
    server.create("van", { id: "4", name: "Dreamfinder", price: 65, description: "Dreamfinder is the perfect van to travel in and experience. With a ceiling height of 2.1m, you can stand up in this van and there is great head room. The floor is a beautiful glass-reinforced plastic (GRP) which is easy to clean and very hard wearing. A large rear window and large side windows make it really light inside and keep it well ventilated.", imageUrl: "https://assets.scrimba.com/advanced-react/react-router/dreamfinder.png", type: "simple", hostId: "789" })
    server.create("van", { id: "5", name: "The Cruiser", price: 120, description: "The Cruiser is a van for those who love to travel in comfort and luxury. With its many windows, spacious interior and ample storage space, the Cruiser offers a beautiful view wherever you go.", imageUrl: "https://assets.scrimba.com/advanced-react/react-router/the-cruiser.png", type: "luxury", hostId: "789" })
    server.create("van", { id: "6", name: "Green Wonder", price: 70, description: "With this van, you can take your travel life to the next level. The Green Wonder is a sustainable vehicle that's perfect for people who are looking for a stylish, eco-friendly mode of transport that can go anywhere.", imageUrl: "https://assets.scrimba.com/advanced-react/react-router/green-wonder.png", type: "rugged", hostId: "123" })
},

routes() {
    this.namespace = "api"
    this.logging = false
    this.get("/vans", (schema, request) => {
        return new Response(400, {}, {error: "Error fetching data"})
        //return schema.vans.all()
    })
    
    this.get("/vans/:id", (schema, request) => {
        const id = request.params.id
        return schema.vans.find(id)
    })

    this.get("/host/vans", (schema, request) => {
        // Hard-code the hostId for now
        return schema.vans.where({ hostId: "123" })
    })

    this.get("/host/vans/:id", (schema, request) => {
        // Hard-code the hostId for now
        const id = request.params.id
        return schema.vans.findBy({ id, hostId: "123" })
    })
}
})

字符串
api.js是:

export async function getVans() {
  const res = await fetch("/api/vans")
  if (!res.ok) {
  throw Object.assign(new Error("Failed to fetch vans"),{
      message: "Failed to fetch vans", 
      statusText: res.statusText,
      status: res.status
  });
  }
  const data = await res.json()
  return data.vans
}


下面是我的fetch代码:

export async function getVans() {
  const res = await fetch("/api/vans")
  if (!res.ok) {
  throw Object.assign(new Error("Failed to fetch vans"),{
      message: "Failed to fetch vans", 
      statusText: res.statusText,
      status: res.status
  });
 }
  const data = await res.json()
  return data.vans
}


我在我的组件中使用它来设置一些状态。
我在use effect中调用此API时使用了try-catch块。但是我看到错误没有被抓住。

useEffect(() => {
async function loadVans() {
  setLoading(true)
  try {
      const data = await getVans()
      console.log("fetched data: "+data);
      setVans(data)
  } catch (err) {
    console.log("error :"+err)
      setError(err)
  } finally {
      setLoading(false)
  }
}
loadVans()
}, [])


我看到它继续运行,并因运行时错误而中断。以下是该项目的链接:https://github.com/manjosh1990/react-practice/tree/master/reactive-navigation
不知何故,即使我在server.js中返回400,响应也是200。x1c 0d1x的数据
我在/vans路径上得到错误。文件是Vans.jsx



Vans.jsx是:

import React from "react";
import { useState, useEffect } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { getVans } from "../../api";

export default function Vans() {
  const [vans, setVans] = useState([])
  const [searchParams, setSearchParams] = useSearchParams();
  const [loading,setLoading] = useState(false);
  const [error, setError] = useState(null);

  const typeFilter = searchParams.get("type");
  useEffect(() => {
    async function loadVans() {
      setLoading(true)
      try {
          const data = await getVans()
          console.log("fetched data: "+data);
          setVans(data)
      } catch (err) {
        console.log("error :"+err)
          setError(err)
      } finally {
          setLoading(false)
      }
    }
    loadVans()
}, [])

  const displayedVans = typeFilter
        ? vans.filter(van => van.type === typeFilter)
        : vans
  console.log("typeFilter :" + typeFilter);
  const vanElements = displayedVans.map(van => {
    return (
      <div key={van.id} className="van-tile">
        <Link to={van.id} state={{ search: `? 
   ${searchParams.toString()}`, type: typeFilter }}>
          <img src={van.imageUrl} alt={van.name} />
          <div className="van-info">
            <h3>{van.name}</h3>
            <p>${van.price}<span>/day</span></p>
          </div>
          <i className={`van-type ${van.type} selected`}>{van.type}</i>
        </Link>
      </div>
    )
  })
  function handleFilterChange(key, value) {

    setSearchParams(prevParams => {
      if (value === null) {
        prevParams.delete(key)
      } else {
        prevParams.set(key, value)
      }
  return prevParams
    })
  }
  if(loading){
    return(<h1>Loading</h1>)
  }
  if (error) {
    return <h1>There was an error: {error.message}</h1>
}
  return (
    <div className="van-list-container">
      <h1>Explore our van options</h1>
      <div className="van-list-filter-buttons">
        <button
          onClick={() => handleFilterChange("type", "simple")}
          className={
            `van-type simple ${typeFilter === "simple" ? "selected" : ""}`
          }
        >Simple</button>
        <button
          onClick={() => handleFilterChange("type", "luxury")}
          className={
            `van-type luxury ${typeFilter === "luxury" ? "selected" : ""}`
      }
    >Luxury</button>
    <button
      onClick={() => handleFilterChange("type", "rugged")}
      className={
        `van-type rugged ${typeFilter === "rugged" ? "selected" : ""}`
      }
    >Rugged</button>
    {typeFilter ? (<button onClick={() => setSearchParams({})} className="van-type clear-filters">Clear Filters</button>) : null}
  </div>
  <div className="van-list">
    {vanElements}
  </div>
</div>
  )
}


请指示。

2vuwiymt

2vuwiymt1#

检查这个CodeSandbox,它捕获了getVans函数的错误。

import React, { useEffect, useState } from "react";
import "./styles.css";

async function getVans() {
  throw Object.assign(new Error("Failed to fetch vans"), {
    message: "Failed to fetch vans"
  });
}

export default function App() {
  const [counter, setCounter] = useState(1);

  useEffect(() => {
    async function loadVans() {
      try {
        const data = await getVans();
        console.log("fetched data: " + data);
      } catch (err) {
        console.log("error :" + err);
      } finally {
      }
    }
    loadVans();
  }, [counter]);

  const onClick = () => {
    setCounter(counter + 1);
  };
  return (
    <div className="App">
      <button onClick={onClick}>click me trigger caught error</button>
    </div>
  );
}

字符串
我希望我能指出错误是什么,但如果没有一个“工作”的例子,这是很难从你的结束。

vjhs03f7

vjhs03f72#

问题出在server.js中的导入。未导入Response
import { createServer, Model, Response } from "miragejs"的工作很好。

rn0zuynd

rn0zuynd3#

AJAX and APIs - React
注意:这里处理错误很重要
而不是catch()块,这样我们就不会吞下
组件中实际错误的例外。

ki1q1bka

ki1q1bka4#

import { useEffect } from "react";

// simulate api call
export async function fetchRandomUser() {
  const response = await fetch("https://randomuser.me/api/");
  // If response is ok
  if (response.ok) {
    return response.json();
  } else {
    // else throw your custom error message
    throw new Error("error");
  }
}

export default function App() {
  useEffect(() => {
    async function fetchUsers() {
      try {
       // call user's api
        const users = await fetchRandomUser();
        console.log(users.results);
      } catch (error) {
        // handle error
        console.log("Error", error.message);
      }
    }
    fetchUsers();
  }, []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
    </div>
  );
}

字符串

相关问题