I am building a Ionic app that is supposed to communicate with an ASP net MVC application (I need to get JSON data).
When I send request to the ASP application from the Ionic app, I am not allowed because I am not logged. I get this :
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8100' is therefore not allowed
access. The response had HTTP status code 401.
My issue is that I want to log in to my API but I do not know how to proceed with Ionic. In a similar application, I used C# client and I was using an HttpWebRequest & NetworkCredential objects.
I made POST request to try to log in the API but I just get a 401 error.
Here is the code, but the credentials that I sent do not allow me to authenticate to the web service.
connect(){
var credentials = "name=" + mylogin + "&password=" + mypassword;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post(URLServeur, credentials, {headers: headers}).subscribe(data => {
if(data.json().success){
console.log("yes");
resolve(true);
}
else
{
console.log("no");
resolve(false);
}
});
}
Thanks,
I finaly found out that it is an issue in Angular with the parameters of the request. If you insert too much request options, withCredentials : true is ignored.
Code in Ionic app:
var headers = new Headers();
headers.append('Content-Type', 'application/json');
var url = "http://localhost"
var data = "This is my data";
this.http.post(url, JSON.stringify(data), {withCredentials: true}).subscribe(data => {
if(data){
console.log("yes");
}
else
{
console.log("no");
}
});
Also, do not forget to add this to webConfig file on server :
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="http://localhost:8100" />
<add name="Access-Control-Allow-Headers" value="content-Type,authorization" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
I hope it will help other people
Related
I'm trying to make and api service based in gentritabazi01/Clean-Laravel-Api and larapi with Laravel8. I can't solve the problem with CORS when i make request from different servers to my api . The related is the following:
Access to XMLHttpRequest at 'https://dev.......com/users' from origin 'http://segu........com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Since 2 days ago, i was reading documentation from CORS and Laravel and any solution solve my problem. I tried creating a middleware and add the necessary headers:
//Infrastructure\Http\Middlewares\Cors
<?php
use Closure;
class Cors
{
public function handle($request, Closure $next)
{
return $next($request)
//Url a la que se le dará acceso en las peticiones
->header("Access-Control-Allow-Origin", "*")
//Métodos que a los que se da acceso
->header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
//Headers de la petición
->header("Access-Control-Allow-Headers", "*");
}
}
I tried to using the package Fruitcake from laravel, like is used on base proyect.
//Infrastructur/Http/Kernel.php
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Infrastructure\Http\Middlewares\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\Fruitcake\Cors\HandleCors::class,
];
I tried to add the headers missed in index.php file on /public folder.
//public/index.php
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset = UTF-8');
Someone knows how to solve it? I can add more code if was necessary.
Finally, i find a solution.
I removed all related with cors in my project and i added this in public/web.config file:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
i write this inside system.webServer markup and my project starts to work again.
I currently have a VueJS frontend server where I make ajax requests using axios to my ASP.NET 3.1 backend API. When starting my project in debug or release in Visual studio, my form correctly works. The problem occurs only when publishing my web API on IIS. I've got a CORS Policy allow anything basically in my Web API's startup.
Cors Policy under Startup#ConfigureServices
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
Enabling my policy under Startup#Configure
app.UseCors("CorsPolicy");
Here is my axios request :
let data = new FormData()
if(this.file !== null)
data.append("Icons", this.file.file, this.file.file.name)
data.append('Id', this.itemId)
// append other data...
axios.defaults.headers.common['Authorization'] = 'Bearer ' + this.$store.state.token
axios.post(this.$store.state.api + 'items/edit', data).then(() => {
console.log('success')
}).catch(err => {
console.log(err)
})
The request is successful when no image is provided in the FormData. However, when an image is sent, it returns an error :
Access to XMLHttpRequest at 'https://exemple.com:5001/api/items/edit' from origin 'http://exemple.com has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This error only occurs when my application is published on IIS (6.2)
Using the comments by Lex Li and Brando Zhang, I added a CORS configuration to my web.config of the Web API project.
CORS Configuration :
<cors enabled="true">
<add origin="*" >
<allowHeaders allowAllRequestedHeaders="true" />
</add>
</cors>
I'm creating a small forum where people in our company can put up adverts for goods or services they want to sell on the fly, using aurelia. I have a list of adverts page working fine, a details page for each advert working fine both using get requests from an api. However i can't seem to get the work the Post reqeust when someone wants to add a comment on an advert.
#inject(HttpClient)
export class ApiData {
constructor(httpClient) {
httpClient.configure(config => {
config
.withBaseUrl("MyUrl");
});
this.http = httpClient;
//.configure(x => {x.withHeader('Content-Type', 'application/json');});
}
postAdvertComment(comment, id) {
return this.http.fetch(`/adverts/${id}/comments`, {
method: "post",
body: json(comment),
headers: {
'Accept': 'application/json'
}
});
}
getAdverts() {
return this.http.fetch("/adverts")
.then(response => {
return this.adverts = response.json();
});
}
getAdvert(id) {
return this.http.fetch(`/adverts/${id}`)
.then(response => {
return this.advert = response.json();
});
}
}
Doing this project we've had some issue with CORS, all solved by adding in AllowCors tags in the api, including all methods etc.
<add key="CorsAllowedOrigins" value="*" />
<add key="CorsAllowedHeaders" value="" />
<add key="CorsAllowedMethods" value="*" />
However when i try and run the post, its running an options method and returns a 400 Bad request.
Here
We also get the following CORS error:
Fetch API cannot load MyURL/api/adverts/2/comments. Response to preflight
request doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'http://localhost:49877' is
therefore not allowed access. The response had HTTP status code 400. If an
opaque response serves your needs, set the request's mode to 'no-cors' to fetch
the resource with CORS disabled.
I don't know if it's a problem with our c# api or with how I'm trying to post from aurelia, but we have tried sending requests from postman and it works fine, tried sending post request within the same app using jquery and it works fine, and all the get requests work fine, but for some reason this post is causing all sorts of problems.
It seems to be a problem in your WebAPI, but before giving you some possible solutions I'd like to show you some important things.
Postman is not affected by CORS, so all requests work.
jQuery ajax uses XHR (XmlHttpRequest object) while aurelia-fetch-client uses fetch (window.fetch. However, the fetch-polyfill uses XHR in the background). They are
different approaches to solve the same problem. Just because one of them work, doesn't actually mean that the other one should work too.
The OPTIONS request is made by fetch, that's how it works. More information here https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en
To solve this problem try to remove those tags from web.config, and allow CORS in your Startup.cs. Like this:
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll); //or another parameter
//rest of your code
}
You don't have to set the content-type header to application/json. It is automatically made when you use the json() function ---> body: json(comment)
If you are using OWIN you might have to send the content-type as x-www-form-urlenconded. In that case, take a look at this Post 'x-www-form-urlencoded' content with aurelia-fetch-client
I am just trying to use mocky.io from my http://localhost:8080
But getting this error:
XMLHttpRequest cannot load http://www.mocky.io/v2/5715f13a1100004d1187d9e1. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
My request looking like that:
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
this.people = http.get('http://www.mocky.io/v2/5715f13a1100004d1187d9e1', { headers: headers })
.map(response => response.json());
Actually you should setup the header Access-Control-Allow-Origin in mocky.io.
Just click on "Switch to Advanced mode" and you will see a "custom headers" input. Add Access-Control-Allow-Origin and put * as its value. Then create your mocky.io url. It should work now.
It is looks like you are trying to access to other domain.
Maybe add this in the web.config?
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="http://localhost" /> </customHeaders> </httpProtocol>
I'm trying to call a WCF service using jQuery in asp.net
WCF service and asp.net website is under the same solution, however they run in different ports as below
WCF - http://127.0.0.1:54443/Service1.svc/
asp.net - http://127.0.0.1:57484/WebSite2/
Below is the WCF function code
[WebInvoke(Method = "GET",RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
public List<string> getCurrentTime()
{
List<string> lstrSampleDate = new List<string>();
lstrSampleDate.Add(DateTime.Now.TimeOfDay.ToString());
return lstrSampleDate;
}
and below is jquery code
$.ajax({
type: "GET",
url: "http://127.0.0.1:54443/Service1.svc/getCurrentTime",
// crossDomain: true,
datatype: "json",
success: function (rVal) {
//console.log
alert(rVal);
},
error: function (xhr, status) {
//console.log
alert('Error: ' + xhr.statusText + 'Status: ' + xhr.status);
},
complete: function (xhr, status) {
//console.log
alert("The request is completed!");
}
});
When i execute the code i get the below error get printed in console
> XMLHttpRequest cannot load
> http://127.0.0.1:54443/Service1.svc/getCurrentTime. Origin
> http://127.0.0.1:57484 is not allowed by Access-Control-Allow-Origin.
As a work-around i did add the below settings to config file (of website)
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
and still did get any fruitful result. can anyone point me where i'm missing?
Note: I've replaced 'localhost' with 127.0.0.1
Thanks
May be you'll find this post helpful: Access-Control-Allow-Origin error sending a jQuery Post to Google API's
I solved the Access-Control-Allow-Origin error modifying the dataType
parameter to dataType:'jsonp' and adding a crossDomain:true