I have the CORS problem with axios or fetch with different configurations, these are my codes:
For fetch:
fetch(url, {
method: 'GET',
mode: 'cors',
headers: {
Authorization: token,
'Access-Control-Allow-Origin': '*'}
})
.then(response =>
response.ok ? response : Promise.reject<Response>(response)
)
.then(response => response.json())
.then(data => data.Token)
Or for axios
axios.get(url, {
headers: {
Authorization: token,
'Access-Control-Allow-Origin': '*'
},
crossDomain: true
})
.then((response) => {
console.log("sendValidateJWTRequest response", response);
return response.data
}, (error) => {
console.log(error);
return Promise.reject(error);
})
And in my web.config I have:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
I'm still getting in the browser:
What else should I try?
As the comment posted by Lex Li, IIS CORS is a good choice to handle the CORS issue. some Preflighted requests can not be handled properly. In an Asp.net web application, we usually add a global.asax file to process it on the server-side.
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.End();
}
}
However, IIS Core module is a better solution.
1. Install the IIS CORS module on the server-side.
https://www.iis.net/downloads/microsoft/iis-cors-module
2. Here is a common configuration allowing all requests from all origins.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
<cors enabled="true" failUnlistedOrigins="true">
<add origin="*" allowed="true">
<allowHeaders allowAllRequestedHeaders="true"/>
</add>
</cors>
</system.webServer>
</configuration>
That’s all.
For customizing your configurations for a specific origin, please check the below link.
https://learn.microsoft.com/en-us/iis/extensions/cors-module/cors-module-configuration-reference
Feel free to let me know if there is anything I can help with.
Related
In my Mern Stack Project I am facing a problem when I am creating a Lesson from postman its created successfully but when I am trying from my browser its given me 500 error in network tab. But in console i got CORS error and also 500 error. I am including SS in bellow if anyone can face this kind of problem please help me. I am trying all the similiar solution from stackoverflow.
Access to XMLHttpRequest at 'https://lms-api-v1.coderslab.com.bd/api/v1/lesson/add' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
const apiClient = axios.create({
baseURL: "https://my-link",
withCredentials: false,
accesscontrolalloworigin: "*",
accesscontrolallowMethods: "GET, POST, PUT, DELETE, PATCH, OPTIONS",
});
// Create Lesson
export const createLesson = (lessonData, token) => async (dispatch) => {
try {
dispatch({ type: NEW_LESSON_REQUEST });
const config = {
headers: {
Authorization: `Bearer ${token}`,
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Credentials':true,
'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
},
};
const { data } = await apiClient.post(`lesson/add`, lessonData, config);
dispatch({
type: NEW_LESSON_SUCCESS,
payload: data,
});
} catch (error) {
dispatch({
type: NEW_LESSON_FAIL,
payload: error.response,
});
}
};
you need to allow origin from backend. like this
Access-Control-Allow-Origin: http://localhost:3000
Add this in backend
Access-Control-Allow-Origin: '*'
I am getting,
Access to fetch at 'http://localhost:9000/api/v1/content' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
and
for my FE(react)
and getting syntax err for BE(node),
SyntaxError: Unexpected token " in JSON at position 0
I have no issue with GET request but I can't POST.
Here is my FE
addContent = async (e) => {
e.preventDefault();
try {
const response = await fetch('http://localhost:9000/api/v1/content', {
method: 'POST',
body: JSON.stringify(this.state.title),
// mode:'cors', --> tried after researching but it didn't solve my issue
headers: {
'Content-Type': 'application/json'
}
});
if(!response.ok) {
throw Error(response.statusText)
}
} catch (err) {
console.log('addContent failed -', err)
}
}
Here is my BE
origin: ['http://localhost:3000', 'https://localhost:3000'],
credentials: true,
optionsSuccessStatus:200
}
app.use(cors(corsOptions));
Also, when I POST with postman, I was able to POST(got 200) however, it only returns _id. there is no body(content title that I want to post)
I read many articles that explained about cors issue but I couldn't find right answer to solve my issue. Please assume me as beginner of programing.. Thank you ahead!!
Try This
addContent = async (e) => {
e.preventDefault();
try {
const response = await fetch('http://localhost:9000/api/v1/content', {
method: 'POST',
body: JSON.stringify(this.state.title),
// mode:'cors', --> tried after researching but it didn't solve my issue
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
}
});
if(!response.ok) {
throw Error(response.statusText)
}
} catch (err) {
console.log('addContent failed -', err)
}
}
And also you can refer https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
And I suggest try once without using cors at express.
origin: ['http://localhost:3000', 'https://localhost:3000'],
credentials: true,
optionsSuccessStatus:200
}
//app.use(cors(corsOptions));
Your error here, means that you are not allowed to access localhost:9000 from any other URL.
I recommend you take a look at this (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
If you want your API to be accessed by anyone, you can set your "Access-Control-Allow-Origin" header to "*".
Here is a full explanation of this header purpose (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin).
I hope it will be useful.
I'm trying to build a Chrome extension and I need to load/save some data from/to the https://address.com. My manifest.json is as below:
"permissions": [
"geolocation",
"unlimitedStorage",
"https://address.com/"
],
"content_security_policy": "script-src 'self'; object-src 'self';connect-src 'self' https://address.com/;"
But I'm running into the below issue when I'm trying to load, I'm not sure what is the issue and how to fix it.
Refused to connect to 'https://address.com/graphql' because it violates the following Content Security Policy directive: "connect-src 'self' blob: .....
Please suggest, thanks.
Fetch Code:
try {
fetch("https://address.com/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ query: "{ getList(page:1, limit: 10) { t } }" })
})
.then(res => res.json())
.then(res => console.log("getList: ", res.data));
} catch (error) {
console.error("getListError:", error);
}
I just noticed another thing, the code works fine on sites like stackoverflow.com but giving error on facebook, twitter ... any idea.
I don't know why this happens.
When I'm making a request to my server in Node.js and when it's GET then I can get a response. It looks like that:
fetch(config.apiUsersURL, {
method: "GET",
headers: {
"Content-Type": "application/json"
},
credentials: "same-origin",
mode: 'no-cors'
})
.then(res => this.setState({
isConected: true
}))
.catch(error => error);
When I'm requesting to the same url but with POST I'm getting nothing. Am I missing something?
const ObjToSend = { isReady: true };
fetch( config.apiUsersURL, {
method: 'POST',
mode: 'no-cors',
body: JSON.stringify(ObjToSend),
headers: {
"Content-Type": "application/json"
},
credentials: "same-origin",
mode: 'no-cors',
})
.then(res => res.json())
.then(r => this.setState({ questions: r }))
My endpoint looks like that:
let randomProblem2;
router.post('/', (req, resp) => {
resp.append('Access-Control-Allow-Origin', '*')
resp.append('Access-Control-Allow-Headers', 'Content-Type')
console.log("this shows if yes was clicked", req.body)
if(req.body.isReady){ //when clicked
randomProblem2 = problemManager.getRandomProblem();
randomize(randomProblem2, resp);
}
})
function randomize(randomProblem2, resp){
resp.json({
randomProblem : randomProblem2
}
)}
Since the mode you are using is no-cors, you cannot use javascript to access the response
Quoted below from MDN:
no-cors — Prevents the method from being anything other than HEAD, GET
or POST, and the headers from being anything other than simple
headers. If any ServiceWorkers intercept these requests, they may not
add or override any headers except for those that are simple headers.
In addition, JavaScript may not access any properties of the resulting
Response. This ensures that ServiceWorkers do not affect the semantics
of the Web and prevents security and privacy issues arising from
leaking data across domains.
Kindly check the MDN link below for the rest of mode options
https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
I want to show an .mp4 as a background video on a website I created and deployed to Azure via FTP.
Unfortunately, accessing the background video always gives me a 404.
The pages are all .html files using AngularJS.
I figure that I need to add a custom mime type for .mp4s. Normally this would be done in the Web.Config, but since it was just something I whipped up in Notepad++ I don't have (and besides this issue, haven't really had need for) a Web.Config.
I was looking at the Configuration section in the Azure Portal for the site and can see where I can add connection strings and appSettings, but I don't see anything where I can do MIME types.
Is allowing .mp4s on Azure possible through the portal, or is my only option to make a Web.Config and FTP that up too?
The only way to do this is via the Web.config file. This link below will help you configure the settings in web.config:
Use SVG in Windows Azure Websites
I tried the web.config solution but it didn't work out for me because I was using AuthInterceptor to set Headers globally.
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
'Content-Type' : 'application/json; charset=utf-8',
'Accept': 'application/json',
'Authorization': `Bearer ${token_here}`,
},
});
return next.handle(req);
}
}
So, this was also setting up the headers for SVGs and other media files, like in your case for mp4. So, I used to filter the incoming request based on type of request and the type of resource requested. Below is a piece of code:
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.method === 'GET' && req.url.endsWith('.svg')) {
req = req.clone({
setHeaders: {
'Authorization': `Bearer ${btoa("admin:admin")}`,
},
});
}
else {
req = req.clone({
setHeaders: {
'Content-Type': 'application/json; charset=utf-8',
'Accept': 'application/json',
'Authorization': `Bearer ${btoa("admin:admin")}`,
},
});
}
return next.handle(req);
}
}