gpt4 book ai didi

javascript - 主干 POST JSON

转载 作者:行者123 更新时间:2023-11-30 17:38:43 25 4
gpt4 key购买 nike

我是 Backbone 的新手,并且让 GET 与测试端点一起工作,例如,

var Attributes = Backbone.Collection.extend({
url: '//127.0.0.1:8080/blah'
});

var AttributeListView = Backbone.View.extend({
el: '.page',
render: function () {
var that = this;
var attributes = new Attributes();
attributes.fetch({
success: function (attributes) {
var template = _.template($('#attribute-list-template').html(), {attributes: attributes.models});
that.$el.html(template);
}
})
}
})

但是,真正的端点需要一个带有 JSON 有效负载的 POST,我无法使语法正常工作。我试过这样的事情

var AttributeListView = Backbone.View.extend({
el: '.page',
render: function () {
var that = this;
var attributes = new Attributes();
attributes.fetch({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{ "searchtext": "abc" }',
success: function (attributes) {
var template = _.template($('#attribute-list-template').html(), {attributes: attributes.models});
that.$el.html(template);
}
})
}
})

@Rusty,无论有没有 http,URL 都可以正常工作,现在的浏览器可以正确处理它。进一步挖掘后,它似乎是一个 CORS 问题。我知道端点已设置 Access-Control-Allow-Origin:* 但仅适用于 POST 请求,我认为请求设置不正确,这是我从 Chrome 调试中得到的信息

Request URL:http://127.0.0.1:8080/blah
Request Headers CAUTION: Provisional headers are shown.
Accept:application/json, text/javascript, */*; q=0.01
Cache-Control:max-age=0
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Origin:http://localhost:8000
Referer:http://localhost:8000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.102 Safari/537.36
Form Dataview sourceview URL encoded
{ "searchtext": "abc" }:

来自控制台日志

XMLHttpRequest cannot load http://127.0.0.1:8080/blah. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. 

最佳答案

正如您所说,这是一个 CORS 问题。

特别是在 POST PUTDELETE 请求上,浏览器实际上执行了 2 个请求。

在幕后发生的事情是,在真正的请求之前,浏览器发送一个预检 OPTION 请求,这就像请求服务器允许发出实际请求。(请检查服务器日志来自浏览器的请求类型)

要允许 CORS 请求,服务器必须正确处理这种情况并使用一组 CORS header 响应 OPTION 请求,如下所示:

Access-Control-Allow-Origin: http://some.another.domain
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type
Content-Type: text/html; charset=utf-8

在 CORS header (全部以 Access-Control-Allow-* 开头)中,服务器指定以下权限:

  • 允许哪个域执行请求,可以是*来允许任何外部域。
  • 接受来自这些域的哪些 HTTP 方法。
  • 接受哪些请求 header ,您可以添加所有需要的 header 。例如,要处理不同域之间的 HTTP 身份验证,这是使用外部 API 的常见场景,您需要添加授权 header 。

如果服务器正确响应 OPTION 请求,浏览器将执行实际请求。

这是正确处理 Rails CORS 请求的指南,但它很容易适用于所有服务器端语言/框架:http://leopard.in.ua/2012/07/08/using-cors-with-rails/

关于javascript - 主干 POST JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21492655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com