首页 > 解决方案 > GET http://localhost:8000/api/signup net::ERR_ABORTED 404(未找到)

问题描述

我可以通过 Postman 到达这个端点http://localhost:8000/api/signup并返回JSON

发布 http://localhost:8000/api/signup

{
    "name": "Username",
    "email": "username@mail.co",
    "password": "abcedf"
}

响应

{
    "message": "Signup success! Please signin"
}

在我的前端(使用 next.js 构建)中,我试图用来fetch做同样的事情,但出现 3 个错误:

GET http://localhost:8000/api/signup net::ERR_ABORTED 404(未找到)

SyntaxError:在 eval (auth.js?8ae0:18) “错误”处输入意外结束

未捕获(承诺中)TypeError:无法读取未定义的属性“错误”

配置.js

import getConfig from 'next/config'

const { publicRuntimeConfig } = getConfig()

export const API = publicRuntimeConfig.PROD ? 'https://production.website.com' : 'http://localhost:8000'
export const APP_NAME = publicRuntimeConfig.APP_NAME

auth.js

import fetch from 'isomorphic-fetch'
import { API } from '../config'

export const signup = user => {
    // return fetch(`${API}/signup`,
    return fetch(`http://localhost:8000/api/signup`,
        { mode: 'no-cors'},
        {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify(user)
    })
        .then(res => {
            return res.json()
        })
        // .then(data => console.log('success:', data))
        .catch(err => console.log(err, 'error'))
}

SignupComponent.js 中的提交函数

const handleSumbit = e => {
    e.preventDefault()
    // console.table({ name, email, password, error, loading, message, showForm })
    setValues({...values, loading: true, error: false})
    const user = { name, email, password }

    signup(user)
    .then(data => {
        if(data.error) {
            setValues({ ...values, error: data.error, loading: false })
        } else {
            setValues({...values, name: '', email: '', password: '', error: '', loading: false, message: data.message, showForm: false})
        }
    })
}

每次我触发 handleSubmit 时后端服务器控制台

GET /api/signup 404 0.417 ms - 149
GET /api/signup 404 0.516 ms - 149
GET /api/signup 404 0.499 ms - 149
GET /api/signup 404 0.313 ms - 149

我错过了什么?

标签: javascriptapihttp-headers

解决方案


我想是因为你的陈述

 .then(res => {
            return res.json()
        })

你正在使用 fetch 返回一个承诺,你应该 .then() 和 .catch() 函数返回的地方不在函数本身内

signup(user)
    .then(data => {
     do something with data      
})
.catch((err) => handle err))
export const signup = user => {
    // return fetch(`${API}/signup`,
    return fetch(`http://localhost:8000/api/signup`,
        { mode: 'no-cors'},
        {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify(user)
    })

这应该是这个函数的结尾


推荐阅读