javascript - 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
我错过了什么?
解决方案
我想是因为你的陈述
.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)
})
这应该是这个函数的结尾
推荐阅读
- android - 有什么办法可以在编辑 apk 时摆脱“无效的资源目录名称”错误
- python-3.x - 将ffmpeg持续时间值转换为秒的Python代码
- javascript - AppleScript/JavaSript 在 Safari 中突出显示匹配的文本
- javascript - 将 JavaScript 数组传递给 PHP 数组
- python - 已满足要求:c:\anaconda3\lib\site-packages (1.20.1) 中的 numpy
- python - 无法在 google colab 中安装 pyaudio
- python - 删除 Tkinter 中整数条目中的默认 0
- javascript - 视频流不是通过我的 RTCPeerConnection 发送的
- c# - 发布对象数组时从 Web API 接收 405 HTTP 响应(.Net Core 5)
- git - 合并冲突:从分支中提取单个文件时