reactjs - 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 请求,但我看不到它,所以任何帮助或文档将不胜感激。
谢谢,
解决方案
由于您将/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))
推荐阅读
- javascript - 如何从firebase中的函数检索数据
- json - 如何过滤 API 响应以在 Swift 中包含/排除 TableView 中的某些数据
- java - 为什么我们不能通过使用 Character 类的对象来使用 Character 类的方法?
- internet-explorer - 如何禁用 Internet Explorer '该网站已被报告为不安全'
- c++ - 如何在 C++ 中正确使用 ifstreams、子进程并避免泄漏?
- c++ - 你什么时候会使用函数重载而不是默认参数?
- php - 用于匹配 HTML 字符串的正则表达式
- swift - 路由时如何在请求中传递参数(使用 Vapor 的服务器端 Swift)
- java - 如何停止输出空变量?
- android - Android后台任务和电池消耗