gpt4 book ai didi

javascript - jQuery 将 OPTIONS 而不是 POST 请求发送到本地主机上的 REST

转载 作者:行者123 更新时间:2023-11-28 10:56:10 24 4
gpt4 key购买 nike

我正在尝试通过 POST 向我的 REST 资源 (Java) 发送表单,但我无法这样做,因为我的请求改为作为选项发送。我知道 REST 资源很好,因为当我使用 Poster Firefox 测试它时它工作得很好。

jQuery/Ajax 调用:

function loadTwitter(){
arrayTweets = new Array();
var urlTwitter = "http://localhost:8081/streamingvideoservice/services/twitter/retrieveTweets";
$.ajax({
type: "POST",
url: urlTwitter,
contentType: "application/x-www-form-urlencoded",
//accept: "application/json",
data: $("form#mapForm").serialize(),
dataType: "json",
async: false,
success: function (resp, status, xhr) {
$("#message").html("STATUS: " + xhr.status + " " + xhr.statusText + "\n" + resp);
$("#message").hide();
$.each(resp, function() {
$.each(this, function(i, item) {
arrayTweets.push(item);
});

});

displayTweets();
},
error: function(resp, status, xhr){
$("#message").html("ERROR: " + xhr.status + " " + xhr.statusText + "\n" + resp.e);
$("#message").show();
}
});
}

REST 资源:

    @POST
@Path("/retrieveTweets")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces("application/json")
public List<Tweet> retrieve(@FormParam("lat") Double Latitude, @FormParam("lon") Double Longitude, @FormParam("rad") Integer Radius, @FormParam("from") String From, @FormParam("to") String To) {

ArrayList<Tweet> lTweets = new ArrayList<Tweet>();
boolean status = false;

Twitter twitter = new TwitterFactory().getInstance();

AccessToken accessToken = new AccessToken(TwitterInterface.ACCESS_TOKEN, TwitterInterface.ACCESS_TOKEN_SECRET);
twitter.setOAuthConsumer(TwitterInterface.CONSUMER_KEY, TwitterInterface.CONSUMER_SECRET);
twitter.setOAuthAccessToken(accessToken);

try {
Query query = new Query("");
GeoLocation geo = new GeoLocation(Latitude, Longitude);
query.setGeoCode(geo, Radius, Query.KILOMETERS);
query.setCount(100);
query.setSince(From);
query.setUntil(To);
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText() + " - " + tweet.getCreatedAt());
Tweet t = new Tweet();
t.setUser(tweet.getUser().getScreenName());
t.setText(tweet.getText());
lTweets.add(t);
}
}
catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}

return lTweets;

}

我正在使用 jQuery 1.9.1 并在 Tomcat 6 上托管资源。

感谢任何帮助。

提前致谢。

最佳答案

您似乎正在发出跨源 Ajax 请求。这需要服务器提供 Access-Control-Allow-Origin header ,以向托管包含 JS 的页面的站点授予读取数据的权限。

有关请求的某些信息(可能是 jQuery 添加到 Ajax 请求的 X-Requested-With header )正在触发 preflight request它使用 OPTIONS 请求在发出主请求之前向服务器请求许可。

您需要配置服务器以根据 CORS 规范(上面链接)提供带有适当访问控制 header 的 OPTIONS 响应。

关于javascript - jQuery 将 OPTIONS 而不是 POST 请求发送到本地主机上的 REST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22253582/

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