Nuxt Server-Side Proxy for Open Weather Api

Intro

A common problem when using open weather api is Cross-Origin Resource Sharing (CORS) issues. This typically happens when you’re trying to make an API call from a web application running in a browser, and the browser blocks the request …


This content originally appeared on DEV Community and was authored by Hasibul Alam Ratul

Intro

A common problem when using open weather api is Cross-Origin Resource Sharing (CORS) issues. This typically happens when you're trying to make an API call from a web application running in a browser, and the browser blocks the request because the API server does not include the necessary CORS headers in its response. The quickest fix is to add a cors header however, as we do not control the api server we can not add a cors header even if we wanted too.

Solutions

There are many ways of resolving this issue but below two are the ones I tested and have worked for me.

CORS Anywhere

One service I found that worked for me was CORS Anywhere which adds CORS headers to the proxied request. To use it, we will need to append the hosted NodeJs server url before the api url. Keep in mind that the public instance has a limited number of requests, so it's a good idea to host your own using the CORS Anywhere repository.

For example:

https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/weather?q=london&APPID={apikey}

Personally, for small projects, I prefer not to juggle multiple codebases (maybe I'm just a bit lazy 🤣). With NuxtJs, you can get everything done with less fuss and even add some extra features. I'm sure you can do the same with NextJs and serverless functions.

Nuxt Server-Side Proxy

To start create a file in the api folder on nuxt server directory. I named it weather.js. As nuxt has a file based routing the endpoint will be /api/weather

File structure

root
├─ server
│  ├─ api
│  │  └─ weather.js

Server Side

In the code snippet below, I'm setting up a basic API handler to get weather data using the fetch function. If you're more into axios, feel free to swap it in instead.

import { getQuery } from 'h3';

export default defineEventHandler(async (event) => {
  // Extract query parameters from the event using getQuery
  const { query } = getQuery(event);

  // Access runtime configuration to retrieve the API key for OpenWeatherMap
  const config = useRuntimeConfig();
  const apiKey = config.private.openWeatherApiKey;

  // Construct the API URL for the weather request
  const apiUrl = `https://api.openweathermap.org/data/2.5/${query}&units=metric&appid=${apiKey}`;

  try {
    const response = await fetch(apiUrl);
    if (!response.ok) {
      return {
        statusCode: response.status,
        body: { message: response.statusText },
      };
    }
    const data = await response.json();
    return {
      status: 200,
      message: 'Weather fetched successfully',
      data,
    };
  } catch (error) {
    return {
      statusCode: 500,
      body: { message: 'Internal Server Error' },
    };
  }
});

One cool thing I noticed about using this setup is that it hides both the API URL and the API key.

Original URL: https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=${apiKey}
Masked URL: https://atmosdev.netlify.app/api/weather?query=weather?q=London

So, not only does it simplify the URL, but it also keeps your API key under wraps.

Client Side

Now, all you need to do is pass in the query and fetch the data on the client side, and you're good to go!

const getWeather = async (event) => {
  try {
    const response = await $fetch(`/api/weather?query=London`);
    if (response.status === 200) {
      weather.value = response.data;
    } else {
      console.error("No data returned from the API");
    }
  } catch (error) {
    console.error("Error fetching weather data:", error);
  }
};

Here is the API response data
API response

Deployed App

https://atmosapp.netlify.app/


This content originally appeared on DEV Community and was authored by Hasibul Alam Ratul


Print Share Comment Cite Upload Translate Updates
APA

Hasibul Alam Ratul | Sciencx (2024-08-11T13:49:37+00:00) Nuxt Server-Side Proxy for Open Weather Api. Retrieved from https://www.scien.cx/2024/08/11/nuxt-server-side-proxy-for-open-weather-api/

MLA
" » Nuxt Server-Side Proxy for Open Weather Api." Hasibul Alam Ratul | Sciencx - Sunday August 11, 2024, https://www.scien.cx/2024/08/11/nuxt-server-side-proxy-for-open-weather-api/
HARVARD
Hasibul Alam Ratul | Sciencx Sunday August 11, 2024 » Nuxt Server-Side Proxy for Open Weather Api., viewed ,<https://www.scien.cx/2024/08/11/nuxt-server-side-proxy-for-open-weather-api/>
VANCOUVER
Hasibul Alam Ratul | Sciencx - » Nuxt Server-Side Proxy for Open Weather Api. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/11/nuxt-server-side-proxy-for-open-weather-api/
CHICAGO
" » Nuxt Server-Side Proxy for Open Weather Api." Hasibul Alam Ratul | Sciencx - Accessed . https://www.scien.cx/2024/08/11/nuxt-server-side-proxy-for-open-weather-api/
IEEE
" » Nuxt Server-Side Proxy for Open Weather Api." Hasibul Alam Ratul | Sciencx [Online]. Available: https://www.scien.cx/2024/08/11/nuxt-server-side-proxy-for-open-weather-api/. [Accessed: ]
rf:citation
» Nuxt Server-Side Proxy for Open Weather Api | Hasibul Alam Ratul | Sciencx | https://www.scien.cx/2024/08/11/nuxt-server-side-proxy-for-open-weather-api/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.