问题
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.
- 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.
- 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.
- 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