I am using React.js 18 version. Facing CORS issue on a piece of code while making post request using axios. Intentionally not putting the original URL of post request. Attaching API response screenshot files below the code.
I am getting response in postman but not in browser(CORS). All I know from my colleague, this API is build on PHP and according to backend guy things are fine on his side.
I am putting this code here to know what are we doing wrong on front end? We are stuck here since yesterday.
Please help!
console response : https://i.stack.imgur.com/HbUjq.png
network response : https://i.stack.imgur.com/6xycq.png
network response : https://i.stack.imgur.com/5cjey.png
postman response : https://i.stack.imgur.com/MxyDT.png
import React, {useState, useEffect} from 'react';
import axios from 'axios';
import './App.css';
function App() {
const [CaseDetail, setCaseDetail] = useState([]);
const getCaseDetail = async () => {
const casedetail = {schemeNameDratDrtId:'1',casetypeId:'1',caseNo:'1',caseYear:"2020"};
await axios.post('URL', casedetail,
{
headers: {"Access-Control-Allow-Origin": "*"}
}
)
.then((result) => {
setCaseDetail(result.data.data)
})
}
useEffect(() => {
getCaseDetail();
}, []);
console.log(CaseDetail)
return (
<div className="App">
<h2>Welcome to Home Page</h2>
</div>
);
}
export default App;
Your server should enable the cross-origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms
This is a security issue from the browser. If you get 200 using postman, this means the problem is that the browser is blocking it. Try to play this again using API testing website like: "reqbin.com", if that works, the backend guys should fix the header problem. I hope this helps.
some possiable things that might help:
I am getting response in postman but not in browser(CORS) - this is noraml for CORS problem.
there can be a differnce betweeen fetach and axios requests. so check if fetach works. if so check
Axios fails CORS but fetch works fine
if you need to send a token in a header , make sure that the axios sends it
see
How to set header and options in axios?
Related
I'm making app by using react which is gonna catch data from twitter API
that's my code
import {useEffect, useState, useContext} from 'react'
import {Link, useParams, useNavigate, useLocation} from 'react-router-dom'
export default function Home(){
const [content, setContent] = useState();
const token = 'here is the required token but i cant show you that'
useEffect(() => {
const url = 'https://api.twitter.com/1.1/search/tweets.json?q=something';
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
}
})
.then((response) => {
if(response.status === 404){
console.log('404');
}
else{
console.log(response.status)
console.log('3')
}
})
.then((data) => {
console.log("abba")
console.log(data)
setContent(data)
})
.catch((e) => {
console.log(e.message);
})
}, [])
return(<div>{content}</div>)
}
and i'm getting this type of error
Access to fetch at 'https://api.twitter.com/1.1/search/tweets.json?q=ewron' from origin 'http://localhost:3000' has been blocked by CORS policy:
When I'm catching data by using the same token by using postman everything works fine
I tried to find solution but everyone is refering to backend set on the same machine. How can I solve it in my case ?
A CORS policy is an important feature that prevents other, external websites from accessing an API.
Some APIs have CORS enabled, others have it disabled. And the whitelist will be tailored to the needs/preferences of the developers of that API.
Twitter will, perhaps, allow twitter.com to use Twitter's public api's. Along with other domains they use. Or maybe none at all, idk how their CORS policy is setup. They'll surely have a bit about it in the API docs.
The reason it works for you on postman is that you're not calling it from a website running in your browser, you're calling it from your computer - which is acting as a sort of 'back-end server'. Which is not a CORS policy violation, so it works fine for you.
It's important to note that CORS policies are being enforced by your browser - theoretically, the API has no idea if the request is from a website or a server. Your browser is telling on you, more or less. So it's not a guarantee of security or anything, but it's a pretty decent guard against it.
All of this is to say -- if you want to use their API, you'll want to set up your own routes and have your front-end call on your own backend server/API, and in turn have that call the twitter API. Which is what I'm guessing other people were trying to tell you.
I'm making a React application, and to do API calls in development, I have a proxy set up in my package.json:
"proxy":"https://www.metaweather.com/api/location",
I'm making an api request to a weather app like so:
export const getLocations = async (query) => {
const response = await axios.get(`/search/?query=${query}`)//full address is proxied in package.json
return response.data //WORKS PERFECTLY
}
However, I cannot make an api request to a different url of the same domain, due to a CORS error
export const getWeather = async (id) => {
const response = await axios.get(`44418`)
return response.data //CORS PROBLEM
}
How can I fix this? I've been searching all day, and cannot figure out why one subdomain will work but the other won't?
Could it be the missing '/' at the start of the zip code? Don't know what the endpoint looks like but if you've configured cors options on that /location route maybe it's not hitting it right.
I have a backend with laravel sanctum implementation, all config are working correctly.
On the frontend I use react, an action is dispatched to login, for example.
X-XSRF-TOKEN must be set before hitting the endpoint, thus I must call /sanctum/csrf-cookie first, I've ran into these problems:
If I try and get the csrf token in createAsyncThunk first, and then /login, redux toolkit assumes the request is fulfilled, thus changing the state before the login api is called
I have no idea why when I create an axios instance, the X-XSRF-TOKEN is not being set in the header, but when I use axios imported normally, it works.
Action
export const login = createAsyncThunk("auth/login", async (_) => {
try {
request.get("sanctum/csrf-cookie").then((response) => {
// THE PROBLEM OCCURS HERE, no header is received, (request is instantiated below, if I import axios it works)
const res = await request.post("/login", _);
return res.data;
// this one failed with 419 csrf token mismatch, eventually because X-XSRF-TOKEN is not set, im not sure why
});
} catch (err) {
throw err;
}
});
axios
import axios from "axios";
export const request = axios.create({
baseURL: `http://localhost:8000/`,
headers: {
Accept: "application/json",
},
});
axios.defaults.withCredentials = true;
Note: The backend is working and configued correctly, because if I do not create an instance and just import and use axios, the request is working, but I'm back with problem 1, where the thunk is fulfilled on the first request (before return response.data), and i'm not interested in such a solution, I don't need to copy the code
Summary:
The sanctum/csrf-cookie response has no X-XSRF-TOKEN header, only when creating an axios instance using axios.create, a cookie is received though
Perhaps the header is resetting to its default on the second request? how can I append the headers from the first request? Thanks
-- Should I try instead of calling sanctum/csrf-cookie in all requests like this, intercept the request and somehow append the header to the request?
Any help, examples, guides are appreciated
rookie mistake, was using axios.defaults.withCredentials = true;
instead of axiosInstance.defaults.withCredentials = true;
I'm making react app which search on Youtube and show some list of video by using create-react-app.
My problem is the document of response from axios.get() only contains scripts and empty skeleton tag.
I want this has some contents inside of it like when opened from browser. why this happen? and what should i study?
import React from "react";
import SearchBar from "./SearchBar";
import axios from "axios";
class App extends React.Component {
onSubmitFormSearch = async (text) => {
console.log("axios", text);
const response = await axios.get(`/results?search_query=${text}`, {
responseType: "text",
responseEncoding: "utf8",
});
console.log(response.data);
};
render() {
return <SearchBar onSubmitForm={this.onSubmitFormSearch} />;
}
}
export default App;
this is my react code
here's document of response https://codepen.io/im0505/pen/MWaMKXa
You will not get the complete webpage just like you see in browser when visualising the response of axios.get. The fundamental reason is that when you load an URL in browser, browser executes the scripts from the response of the request which doesn't happen when visualising response of request made by axios.
What Happens When You Type in a URL : Source
You enter a URL into a web browser
The browser looks up the IP address for the domain name via DNS
The browser sends a HTTP request to the server
The server sends back a HTTP response
The browser begins rendering the HTML
The browser sends requests for additional objects embedded in HTML (images, css, JavaScript) and repeats steps 3-5.
Once the page is loaded, the browser sends further async requests as needed.
Points 6 and 7 doesn't happen when you are looking at the result in Codepen or in your axios response
I am trying to create a post using LARAVEL 5.7 local REST api using a React app. I am using axios.post method with crossOrigin:true . I do not understand why get is working and post is not working. Laravel api is on wamp based localhost and React app is running at localhost:3000 My actions/index.js is as follows and the relevant action creator is addPost():-
import axios from 'axios';
export const FETCH = 'FETCH_POSTS';
export const ADD = 'ADD_POST';
const URL = 'http://postsapi.test/api/v1';
export function fetchPosts(){
const url = `${URL}/posts`;
const request = axios.get(url, { crossDomain: true });
//console.log(request);
return{
type: FETCH,
payload: request
}
}
export function addPost(post){
const url = `${URL}/posts`;
console.log(url);
const request = axios.post(url,post);
//console.log(request);
return{
type: ADD,
payload: request
}
}
This is the snap shot from browser that shows in preflighted request Access-Control-Allo-Origin is set twice as well
And in console I am getting this issue
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://postsapi.test/api/v1/posts. (Reason:
Multiple CORS header ‘Access-Control-Allow-Origin’ not allowed).
This happens because the server and client is on different origins.
To overcome this you have to enable Cross-Origin Resource Sharing in your Laravel server as a middleware.
This thread might help you.