简体   繁体   English

Gatsby.js-表示服务器的代理

[英]Gatsby.js - proxy to express server

I want to setup proxy for my simple express server. 我想为我的简单快递服务器设置代理。 I have added cors policy and everything works perfect when I call api like this: 我添加了cors政策,当我像这样调用api时,一切工作正常:

fetch('http://localhost:3000/tasks')

But when i setup proxy in gatsby.config.js like this: 但是当我在gatsby.config.js中设置代理时,如下所示:

proxy: {
    prefix: '/',
    url: 'http://localhost:3000'
  },

and call: 并致电:

fetch('/tasks)

I'm getting this error: 我收到此错误:

Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0 未处理的拒绝(SyntaxError):JSON中位置0处的意外令牌<

How to setup properly proxy in gatsby.js ?? 如何在gatsby.js中正确设置代理?

This should go into a comment, but format is not good so i post as answer. 这应该发表评论,但是格式不好,所以我将其发布为答案。 I'm not sure what's the precise cause, but some idea to help you debug. 我不确定确切的原因是什么,但是有一些想法可以帮助您进行调试。

  1. Chance are you received a HTML response with content-type header saying it's a JSON. 您可能会收到带有内容类型标头的HTML响应,说它是JSON。 Verify if this is the case by inspecting the network panel in browser devtools. 通过检查浏览器devtools中的网络面板来验证是否是这种情况。
  2. Make sure that request actually hit your express server. 确保该请求实际上命中了您的快递服务器。 If 1. is true, then it's highly likely it didn't reach express server, the HTML comes from Gatsby's dev server. 如果为1.,则很有可能没有到达快递服务器,HTML来自盖茨比的开发服务器。
  3. If both points above are true, then perhaps debug the Gatsby source code to find out why it decide to handle the request instead of forward it. 如果以上两点都正确,那么也许可以调试Gatsby源代码以找出为什么决定处理该请求而不是转发该请求。 Derek Nguyen pointed out the location . 德里克·阮指出了位置 It's also a express server so should be fine to you. 它也是一个快速服务器,因此对您来说应该没问题。

I don't think you can use root as proxy. 我认为您不能将root用作代理。 In gatsby develop, proxy is handled like this : 在盖茨比开发,代理,像这样处理这个

app.use(`${prefix}/*`, (req, res) => { ... }

So if prefix is set to / , it'll become //* which will not work. 因此,如果将prefix设置为/ ,它将变为//* ,这将不起作用。 Even if it did work like /* , all routes from gatsby server will be redirect to proxy server because proxy has higher precedent than the rest of the routes, gatsby wouldn't have any chances to serve any pages at all. 即使它确实像/*一样工作,来自gatsby服务器的所有路由都将被重定向到代理服务器,因为proxy的优先级高于其余路由,但gatsby根本没有机会提供任何页面。

prefix has to be a word started with a slash, ie /api : prefix必须是一个以斜杠开头的单词,即/api

proxy: {
  prefix: '/api',
  url: 'http://localhost:3000'
},

Then you can use it: 然后,您可以使用它:

fetch(`/api/tasks`)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM