next.js 下一个13.4 API路由/服务器操作

7bsow1i6  于 2023-05-28  发布在  其他
关注(0)|答案(1)|浏览(176)

我正在创建一个管理面板与未来13.4,我试图找出为什么我得到一个405错误

export default function NewProduct() {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const[price, setPrice] = useState('');
  async function createProduct(ev) {
    ev.preventDefault();
    const data = {title,description, price};
    //console.log(data)
    await axios.post("/api/products", data);
  }
    return (
        <Layout>
          <form onSubmit={createProduct}>
            <h1>new product</h1>
            <label>Product name</label>
            <input 
              type='text'
              placeholder="product name"
              value={title} 
              onChange={(ev) => setTitle(ev.target.value)}
            />
            <label>description</label>
            <textarea
            placeholder="description"
            value={description}
            onChange={(ev) => setDescription(ev.target.value)}
            />
            <label>
              price (in USD)
            </label>
            <input type="text" placeholder="price"
              value={price}
              onChange={(ev) => setPrice(ev.target.value)}
            />
            <button
             type="submit"
              className="btn-primary">
              Save product
            </button>
          </form>
        </Layout>
    )
}

axios post请求可以工作,但我在开发人员工具中得到了这个:xhr.js:251 POST http://localhost:3000/api/products 405(Method Not Allowed)
我的API/产品:

export default async function handler(req, res) {
    res.json(req.method)
}
des4xlb0

des4xlb01#

如果你想将一个object发送到一个API,你必须将它转换为JSON
推荐的方法是将obj转换为json并保存在cookies中,然后发送给API。
如果你想有一个小的安全选项,首先用公钥签署json obj,并将其保存在cookie(JWT)中。然后发送给API,在API中解密,就可以使用了。
不要忘记如果你收到一个json,你必须解析它,如果你想在API中像obj一样使用它。

相关问题