这里是一些上下文。我有一个使用Gatsby构建的ReactJS网站。该站点是完全静态的,没有后端。我最近一直在进行后端集成,因为我想使用GitHub API做一些datavis的工作。无论如何,我正在使用NodeJS构建自己的后端API,然后代理前端请求(使用fetch API)。
在开发过程中,前端位于localhost:8000,后端位于localhost:5000。这是我的gatsby-config.js
文件。它还有一些与此问题无关的位,但代理位仅在底部:
module.exports = {
siteMetadata: {
title: "Reece Mercer",
description: "Personal website"
},
plugins: [
'gatsby-plugin-react-helmet',
{
resolve: `gatsby-plugin-manifest`,
options: {
name: 'gatsby-starter-default',
short_name: 'Reece Mercer',
start_url: '/',
background_color: '#663399',
theme_color: '#663399',
display: 'minimal-ui',
icon: 'src/assets/images/website-icon.png', // This path is relative to the root of the site.
},
},
'gatsby-plugin-sass',
'gatsby-plugin-offline',
'gatsby-plugin-favicon',
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/blog_posts`,
name: 'blog_posts'
}
},
'gatsby-transformer-remark'
],
proxy: {
prefix: "/myRepoAPI",
url: "http://localhost:5000",
},
}
从本质上讲,从前端到/myRepoAPI/anything
的任何请求都应从前端代理到后端。我已经使用Postman验证了后端,并且该端点可以正常工作。
这是我在前端React组件中使用的访存调用:
componentDidMount(){
fetch('/myRepoAPI/hello')
.then(res => console.log(res))
}
现在分析该控制台日志:
Response {type: "basic", url: "http://localhost:8000/myRepoAPI/hello", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:8000/myRepoAPI/hello"
__proto__: Response
url
值位于本地主机: 8000 ,而不是 5000 。代理无效。我尝试了各种不同的路由组合,跟踪/
,甚至尝试了developMiddleware
的高级代理方法。似乎什么也没有使它正常工作。
任何帮助将不胜感激!
答案 0 :(得分:1)
由于Gatsby的内部开发服务器(默认在端口8000上)处理代理,因此在响应对象中,无论代理是否工作,url
的值始终为http://localhost:8000/...
。
查看本地服务器的端口5000上的日志时,您可能有更多线索,看看Gatsby发出的请求是否实际上已经达到目标;或注销从请求中获得的实际数据。