Gatsby.js - proxy to express server

妖精的绣舞 提交于 2019-12-08 10:37:43

问题


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:

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

But when i setup proxy in gatsby.config.js like this:

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

How to setup properly proxy in gatsby.js ??


回答1:


I don't think you can use root as proxy. 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. 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.

prefix has to be a word started with a slash, i.e /api:

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

Then you can use it:

fetch(`/api/tasks`)



回答2:


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. Verify if this is the case by inspecting the network panel in browser 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.
  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. Derek Nguyen pointed out the location. It's also a express server so should be fine to you.


来源:https://stackoverflow.com/questions/55575953/gatsby-js-proxy-to-express-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!