【发布时间】:2020-07-07 00:07:25
【问题描述】:
我可以通过 Postman 访问此端点 http://localhost:8000/api/signup,它会返回 JSON
POST 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) "error" 处输入意外结束
Uncaught (in promise) TypeError: Cannot read property 'error' of 未定义
config.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
我错过了什么?
【问题讨论】:
-
返回
"JSON",还是返回格式正确的JSON字符串?Unexpected end of input听起来像res.json()无法解析数据。如果不是真正的 JSON,请尝试res.text()。如果没有,你能告诉我们你在 Postman 中得到的结果是什么样的吗? -
我尝试了
res.text(),因为我遇到了错误"SyntaxError: Unexpected token < in JSON at position 0 "error" ",这意味着它返回html而不是Json。这是来自 Postman 的 Json:i.imgur.com/B9S0nyx.png
标签: javascript api http-headers