首页 > 解决方案 > express '/' GET 请求失败,但是 '/' post, put, delete 成功

问题描述

我无法弄清楚我在这里做错了什么,所以眼球或如何解决它的想法将不胜感激

Express (4.17.1) + React (17.0.2)

这工作正常:

router.get('/test', postListView)
router.post('/', postCreateView)

但这失败了:

router.get('/', postListView)

控制器:

const postListView = async (req, res) => {
    // No output from req.method when route is to '/'
    console.log(req.method)
    res.json({message: 'List View'})
}

const postCreateView = async (req, res) => {
    console.log(req.method)
    res.json({message: 'Create View'})
}

我的 POST 请求 React 调用(工作正常):

fetch(`/`,{
  method:'POST',
  headers:{
    'Content-type':'application/json'
  },
  body: JSON.stringify({title:text.current.value})
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err.message))

GET 请求失败:

fetch(`/`)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err.message))

来自 GET 请求的错误:

Unexpected token < in JSON at position 0

我可以通过直接表达(localhost:5000)在浏览器中打开GET请求。

React 正在通过一个“代理”:“http://127.0.0.1:5000”

我想我在这里遗漏了一些基本的 GET 请求,但我看不到它,所以任何帮助或文档将不胜感激。

谢谢,

标签: reactjsexpress

解决方案


由于您将/test其用作 GET 路由的资源路径。最好使用相同的路由从反应应用程序发出 GET 请求。

fetch(`/test`)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err.message))

对于/路径,您需要指定您使用的方法,因为您对 GET 和 POST 请求方法使用相同的路径。

fetch(`/`, { method:'GET' })
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err.message))

推荐阅读