Hossein Ebrahimi
Hossein Ebrahimi

Reputation: 822

502 while trying to proxy requests to API (ASP.NET Core + nuxt)

I have an ASP.NET Core + nuxt setup, and trying to proxy requests that start with /api to the ASP.NET Core Web API (https://localhost:7132/weatherforecast for now).

There's a Youtube video on how to proxy requests in nuxt and it suggests creating a file under the server directory to handle the API routes (at server/api/[...].ts), which I've added:

export default defineEventHandler(async (event) => {
  console.log("inside event");
  const proxyUrl = process.env.NUXT_API_URL;
  console.log("proxyUrl: ", proxyUrl);
  const target = proxyUrl + "/weatherforecast";
  console.log(target); // prints https://localhost:7132/weatherforecast which responds in the browser

  const res = await proxyRequest(event, target);
  console.log("res: ", res); // prints nothing, I assume due to the 502 being thrown at the previous line
  return res;
});

The breakpoint inside the asp.net core route handler doesn't get hit either.

The code is on github.

Update

It's working after setting nitro's devProxy option:

nitro: {
  devProxy: {
    "/api/weatherforecast": {
      target: "https://localhost:7132/weatherforecast",
      secure: false,
    },
  },
},

But I had to keep the server/api/[...].ts file for SSR to work, without that it only works for client-side rendering; which is odd(?!).

Is there a way to set the secure flag within that route handler file so that I can get rid of the nitro devProxy option?

Upvotes: 0

Views: 152

Answers (1)

TechWatching
TechWatching

Reputation: 1547

You can use routeRules instead of devproxy so that it works with SSR. Check this article for the sample on how to do it: https://techwatching.dev/posts/aspnetcore-with-nuxt. This video explains the different strategies to proxy and the ones that work in SSR: https://youtu.be/J4E5uYz5AY8?si=VjdOpJSM-pwLkai8

Upvotes: -1

Related Questions