[英]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.
我不确定确切的原因是什么,但是有一些想法可以帮助您进行调试。
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.