Reputation: 12874
When I directly paste the URL into the browser, I can make the API request successfully. However, when I try it with Axios
I'm hitting below exception
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
Based on some research, I can't understand the logic behind as I'm following the exact same steps provided by online course, by simply firing this API call using Axios should be able to return the result.
import axios from 'axios';
const API_KEY = 'be2e163d03a0b97a96a89b0230be8e4a';
const ROOT_URL = `https://samples.openweathermap.org/data/2.5/forecast?appid=${API_KEY}`
export const FETCH_WEATHER = 'FETCH_WEATHER';
export function fetchWeather(city) {
const url = `${ROOT_URL}&q=${city},my`;
const request = axios.get(url);
return {
type: FETCH_WEATHER,
payload: request
}
}
Upvotes: 2
Views: 2145
Reputation: 1707
You need to add cors in your server app
var cors = require('cors');
app.use(cors());
Hope this help
Upvotes: 1
Reputation: 7368
Here are the few things i observed:
You are using the sample api
(“samples.openweathermap.org”) not the production one
(“api.openweathermap.org”) so i think for integration with application you should use production API.On this they give the CORS support.
If you still want to check with sample api endpoint then
The easy way is to just add the extension in google chrome to allow access using CORS. (https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US)
Just enable this extension whenever you want allow access to no 'access-control-allow-origin'header request.
Or
In Windows, paste this command in run window
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Reference: https://openweathermap.desk.com/customer/portal/questions/16823835-cors
Upvotes: 1
Reputation: 972
When you directly access the url in browser there is no cross domain request is issued. But when you access the resource using axios there might be a chance that you are accessing resource on different domain then the domain present on your browser tab.That is the reason you are getting Access-Control-Allow-Origin not present. For handling this add a logic on server side to add this header in OPTION Response.
Upvotes: 0
Reputation: 74096
This exception means the server your hitting does not support CORS (Cross-Origin Resource Sharing).
In the case of openweathermap.org
I think you should be using api.openweathermap.org
instead of samples.openweathermap.org
Upvotes: 2