0

I need to be able to return a valid JSON response with no HTML wrapping it all. I can accomplish this by specifying a port number pointing directly to my Express backend but need to be able to return pure JSON without having to specify a port number in production. Is there any way to do this if you're using React/React-Router and Express together?

This setup uses a proxy pass to work:

server {
    listen 80;
    listen [::]:80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:5000;
    }
}

Current output: https://socialmaya.com/u/real (1)

Desired output: http://socialmaya.com:5000/actors/real (2)

So I need the output of 1 to be the exact same as 2, ensuring that another server can read it. If you click to View Page Source for both, you can see that the output is not the same.

5
  • For reference, I've asked two other questions related to this issue: stackoverflow.com/questions/61160329/… stackoverflow.com/questions/61162675/… Commented Apr 12, 2020 at 16:40
  • 1
    It seems to me that it's the URI /u/real vs /actors/real that introduces the JSON vs HTML? It has nothing to do with https vs port 5000. Commented Apr 12, 2020 at 17:12
  • That's correct. The reason that I'm only able to access /actors/real via port 5000 is that Express is listening on that port. If I attempt to access that URI via https and without specifying a port number, React/React-Router renders a 404 page. I'm not sure but it seems like React-Router is blocking any access to Express routes unless they're being called within a component. Commented Apr 12, 2020 at 17:19
  • 1
    So is your question, how to rewrite /u/real to /actors/real before passing it upstream? Try rewrite ^/u/(.*)$ /actors/$1 last; Commented Apr 12, 2020 at 17:25
  • This worked, thank you! Is there another way of doing this? This means having to write a rewrite in Nginx for every single route I define with Express. Commented Apr 13, 2020 at 14:15

1 Answer 1

0

Per Richard Smith, rewriting the URL before passing it upstream within Nginx solved my problem:

location / {
    rewrite ^/u/(.*)$ /actors/$1 last;
    proxy_pass http://localhost:5000;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a better way of doing this that doesn't require adding an Nginx rewrite for every route I define with Express that I want to be able to access without specifying a port number, that returns valid JSON, and is able to be reached by the browser or something like curl?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.