如何调试 MERN 上的服务器端错误?
How do I debug server-side errors on MERN?
我有这个前端代码:
export const CreatePage = () => {
const auth = useContext(AuthContext)
const {request} = useHttp()
const [content, setContent] = useState('')
const [title, setTitle] = useState('')
const [lead, setLead] = useState('')
useEffect(() => {
window.M.updateTextFields()
},[])
const postHandler = async () => {
try {
const data = await request('/api/post/generate', 'POST', {title: title, lead: lead, content: content}, {
Authorization: `Bearer ${auth.token}`
})
console.log(data)
} catch (e) {}
}
而这个后端代码:
router.post('/generate', auth, async (req, res) => {
try {
const baseURL = config.get('baseURL')
const {title, lead, content} = req.body
// if (!title || !lead || !content) {
// return res.status(422).json({error: 'Please, input ALL fields'})
// }
const Post = new Post({
title, lead, content, owner: req.body.user.userId // req.user.userId
})
await Post.save()
res.status(201).json({Post})
} catch (e) {
res.status(500).json({message: 'Something went wrong'})
}})
我尝试了很多方法,但仍然出现此错误。我知道这是一个服务器端错误,但这就是我所能弄清楚的。
P.S。代码有什么问题,我会在后面补充。
UPD:顺便问一下,这可能是问题的原因吗?控制台日志:
[1] Proxy error: Could not proxy request /api/post/generate from localhost:3000 to http://localhost:5000.
可能是因为 cors,您无法从不同的 url 发送请求。尝试安装 cors 并配置它:
const cors = require("cors");
app.use("/", require('./src/routes'));
app.use(cors({
origin: '*'
}))
我有这个前端代码:
export const CreatePage = () => {
const auth = useContext(AuthContext)
const {request} = useHttp()
const [content, setContent] = useState('')
const [title, setTitle] = useState('')
const [lead, setLead] = useState('')
useEffect(() => {
window.M.updateTextFields()
},[])
const postHandler = async () => {
try {
const data = await request('/api/post/generate', 'POST', {title: title, lead: lead, content: content}, {
Authorization: `Bearer ${auth.token}`
})
console.log(data)
} catch (e) {}
}
而这个后端代码:
router.post('/generate', auth, async (req, res) => {
try {
const baseURL = config.get('baseURL')
const {title, lead, content} = req.body
// if (!title || !lead || !content) {
// return res.status(422).json({error: 'Please, input ALL fields'})
// }
const Post = new Post({
title, lead, content, owner: req.body.user.userId // req.user.userId
})
await Post.save()
res.status(201).json({Post})
} catch (e) {
res.status(500).json({message: 'Something went wrong'})
}})
我尝试了很多方法,但仍然出现此错误。我知道这是一个服务器端错误,但这就是我所能弄清楚的。
P.S。代码有什么问题,我会在后面补充。
UPD:顺便问一下,这可能是问题的原因吗?控制台日志:
[1] Proxy error: Could not proxy request /api/post/generate from localhost:3000 to http://localhost:5000.
可能是因为 cors,您无法从不同的 url 发送请求。尝试安装 cors 并配置它:
const cors = require("cors");
app.use("/", require('./src/routes'));
app.use(cors({
origin: '*'
}))