我想使用基于ajax的组件(KendoUI)来读取/修改由WCF DataServices实现的OData端点上的实体.
首先,服务实现相当容易:
public class MyFooService : DataService<FooContext>
{
public static void SetEntitySetAccessRules(IDataServiceConfiguration config)
{
config.SetEntitySetAccessRule("Foos", EntitySetRights.AllWrite);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我希望能够使用PUT修改实体.KendoUI提供了一个简单易用的配置界面,在生成PUT请求方面做得很好.
我们正在制作跨域请求并使用CORS.因此,Firefox会在发送PUT之前向OData服务发送预检OPTIONS请求.
不幸的是,服务端点似乎不支持OPTIONS开箱即用:对OPTIONS请求的响应是"501 Not Implemented",内容为空.至少我们管理过响应的CORS头如下:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!-- Enable cross-origin resource sharing -->
<!-- http://enable-cors.org/#how-asp.net -->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE, GET, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="content-Type, accept, origin, X-Requested-With" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
谷歌搜索已经变得有点挑战,因为"选项"是一个非常受欢迎的术语......
我发现这篇文章但看起来非常非常复杂.我的意思是,OData是关于REST的,我无法想象WCF数据服务不提供允许预检请求的简单方法,或者?
我在包含Apache托管的API端点的站点中使用HTTP基本身份验证(用户名和密码),我在.htaccess上执行类似的操作:
AuthType Basic
AuthName "Restricted Files"
# (Following line optional)
AuthBasicProvider file
AuthUserFile /usr/local/apache/passwd/passwords
Require user rbowen
Run Code Online (Sandbox Code Playgroud)
由于我在另一个域上托管的页面中从浏览器端使用API(CORS部分已经解决),我需要允许某些请求未经身份验证.这些请求是请求哪个方法是"OPTIONS",(预检如下所述:http://www.w3.org/TR/cors/#resource-preflight-requests),请,我不需要任何关于ajax的信息或浏览器上的任何其他东西,我需要知道如何在apache上执行此操作
提前致谢
我按照nodejs示例项目(https://github.com/cloudinary/cloudinary_npm/tree/master/samples)开发一个简单的Web应用程序,允许用户上传他们的个人资料图片.当我尝试直接从浏览器上传图像时,我收到错误消息,其中列出了以下消息:
XMLHttpRequest cannot load https://api.cloudinary.com/v1_1/mycloudname/auto/upload. The request was redirected to 'http://localhost:3000/cloudinary_cors.html?bytes=411&created_at=2015-11-23T…s=%23%3CSet%3A0x0000000c75f2e0%3E&type=upload&version=1448287679&width=175', which is disallowed for cross-origin requests that require preflight.
Run Code Online (Sandbox Code Playgroud)
如上所述,问题可能是由于我的节点服务器上的cors支持,所以我回到我的服务器代码并确保回调可以找到cloudinary_cors.html.我再次运行测试,但仍然遇到同样的错误.我设法找到了从控制台上传照片的OPTIONS和POST请求,POST请求返回302(请查找附加的响应消息以供参考),但是可以在Cloudinary仪表板上找到该图像.我怎么能解决这个问题?任何输入将不胜感激!
Remote Address:23.23.xxx.xxx:443
Request URL:https://api.cloudinary.com/v1_1/mycloudname/auto/upload
Request Method:POST
Status Code:302 Found
Response Headers
view source
Access-Control-Allow-Methods:POST, GET, OPTIONS
Access-Control-Allow-Origin:http://localhost:3000
Access-Control-Max-Age:1728000
Cache-Control:no-cache
Connection:keep-alive
Content-Length:840
Content-Type:text/html; charset=utf-8
Date:Mon, 23 Nov 2015 14:07:59 GMT
Location:http://localhost:3000/cloudinary_cors.html?bytes=411&created_at=2015-11-23T14%3A07%3A59Z&delete_token=04963d1a6e5957ee8179c67879c0bc59241f7875fa3a29f430ee7ed942509ea7e0a302627a3b4927ea1cddb2ce2a4028e98d8130b363fdb27901c55a1edb0e9c73e88b027598f3ed1fcc55111ec618d5747d2a16ce80c4036b35d2b778ee81964e2c9014c5e4d796a04b0106f607b9af9bae058c76f4643ccbccaa4fda81968d4728427dfa0ae398fa8322c3760bee45e232336b0464fd0233313d082945e63878d137ddd98e77db9088b6835df8c0905e9e109e3df1add8da50c8b895e503b7&am...
Server:cloudinary
Status:302 Found
X-Request-Id:5dae5c1d34551a10
X-UA-Compatible:IE=Edge,chrome=1
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4
Connection:keep-alive
Content-Length:1197
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryhrzAgVFkPZMRAPo9
Host:api.cloudinary.com
Origin:http://localhost:3000
Referer:http://localhost:3000/users/1234567
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) …Run Code Online (Sandbox Code Playgroud) 我使用axios来调用API(在前端).我使用方法"GET":
import axios from 'axios';
import querystring from 'querystring';
var url = "mydomain.local",
token = "blablabla...blabla";
var configs = {
headers: {
'Authorization': 'Bearer ' + token,
'Agency': 'demo0'
}
};
var testapi = axios.create({
baseURL: 'http://api.' + url
});
testapi.get( '/relativeUrl', configs
).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
Run Code Online (Sandbox Code Playgroud)
我得到了405方法不允许.方法是"OPTIONS",但我使用方法".get()". 405方法不允许.方法选项
我用邮递员测试呼叫api,我得到200 OK:
有人有想法吗?
Chrome版本:57.0.2987
实际上,在较旧的Chrome版本中我也有这个问题.我Authorization在Request Header上添加了访问令牌,
fetch('https://example.com/endpoint', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + accesstoken
}
})
Run Code Online (Sandbox Code Playgroud)
我总是在Chrome中Access-Control-Allow-Headers:authorization使用响应标题除此之外,我的提取始终是请求方法:选项(不显示GET),然后Status Code在Chrome中为200 OK
但是如果我在Firefox(版本52.0.1)中运行相同的获取代码,一切都很好.我可以添加Authorization在请求标题正确.它不会显示Access-Control-Allow-Headers:authorization在响应头在Firefox.它将显示Authorization: Bearer accesstoken在Request标头上.
服务器端已经为我的请求标头处理了CORS ..
这是Chrome错误或我的代码错误?我应该怎么做才能让Authorization在请求头在Chrome是否正确?
我的前端代码:
<form action="" onSubmit={this.search}>
<input type="search" ref={(input) => { this.searchInput = input; }}/>
<button type="submit">??</button>
</form>
// search method:
const baseUrl = 'http://localhost:8000/'; // where the Express server runs
search(e) {
e.preventDefault();
let keyword = this.searchInput.value;
if (keyword !== this.state.lastKeyword) {
this.setState({
lastKeyword: keyword
});
fetch(`${baseUrl}search`, {
method: 'POST',
// mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json'
}),
// credentials: 'include',
body: JSON.stringify({keyword})
})
}
}
Run Code Online (Sandbox Code Playgroud)
和我的Express.js服务器代码:
app.all('*', (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
res.header('Access-Control-Allow-Headers', …Run Code Online (Sandbox Code Playgroud) 我的服务器上有一个从 IIS 运行的简单 GWT 应用程序。我正在尝试测试对在同一服务器上运行的 tomcat 的 HTTP 请求。但是,由于两个应用程序服务器都在不同的端口上运行,因此我的浏览器(chrome 和 firefox)将请求视为 CORS 请求。
为了让 tomcat 能够接受 CORS 请求,我将其更新为 Tomcat 7.0.52 并在全局 web.xml 配置中启用了 CORS 过滤器。我测试了这个简单的设置,它似乎有效。这是 GWT 中的代码:
String url = "http://bavarians:8080/";
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, url);
box.setText(url);
try
{
rb.sendRequest("", new RequestCallback(){
@Override
public void onResponseReceived(Request request, Response response)
{
Window.alert(response.getStatusCode() + response.getStatusText());
}
@Override
public void onError(Request request, Throwable exception)
{
Window.alert("Request failed");
}});
}
catch (RequestException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
这是与之关联的 CORS …
我知道这里已经有很多相同的解决问题,
但不幸的是他们都没有帮助我:-(.
这里我的问题:
我尝试从我的localhost连接到服务器上的REST服务.它与FF REST插件一起工作正常,但我的应用程序导致以下错误:
我如何尝试获取我想要的数据:
@Injectable()
export class ModelsComponent implements OnInit {
private restRoot = 'http://.../my_REST_Service';
private data;
constructor(private http: Http) { }
ngOnInit() {
this.getModels().subscribe(res => {
this.data = res;
console.log(this.data);
});
}
authHeaders() {
let username: string = 'xxxx';
let password: string = 'xxxx';
let token: string = btoa(username + ":" + password);
let headers: Headers = new Headers();
headers.append('Access-Control-Expose-Headers', 'Authorization');
headers.append('Authorization', 'Basic ' + token);
headers.append("Access-Control-Allow-Origin", "http://localhost:4200/");
headers.append("Access-Control-Allow-Methods", "*"); …Run Code Online (Sandbox Code Playgroud) 我正在使用 Web Core API 并按如下方式设置 CORS;
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var url = Configuration["origenUrl"];
var header = "Content-Type";
app.UseCors(
options => options.WithOrigins(url).WithHeaders(header).AllowAnyMethod().AllowCredentials()
);
}
Run Code Online (Sandbox Code Playgroud)
此设置适用于获取请求。但对于我的 Put 请求;
$.ajax({
url: url,
method: "PUT",
xhrFields: { withCredentials: true }
})
.done(callback)
//.fail(errorMessage);
.fail(function (jqXHR, textStatus, errorThrown) {
alert("Something went wrong: " + textStatus + " " + errorThrown);
errorCallback();
});
Run Code Online (Sandbox Code Playgroud)
我收到此错误消息;
XMLHttpRequest 无法加载http://localhost:17972/api/fault/1/close。
对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问来源“ http://localhost:12528 ”。响应的 …