问题描述
Office js 加载项中的此 javascript 在发出获取请求时总是失败:
This javascript within an Office js add-in always fails when making a get request:
function update() {
Excel.run(function (ctx) {
return ctx.sync()
.then(function () {
var company = $('#company').val();
var environment = $('#environment').val();
var apiUrl = "https://localhost:44321/api/Country";
var params = "company=" + company + "&environment=" + environment;
$.getJSON(apiUrl, params)
.done(function (result) {
showNotification(result.length);
})
.fail(function (xhr, status, error) {
//showNotification(error.statusText);
showNotification(error.length);
});
});
}).catch(function (error) {
showNotification(error);
});
}
我可以看到在 Fiddler 中成功返回了 json,并且 JSONLint 说 json 是有效的.这是:
I can see the json being returned successfully within Fiddler and JSONLint says the json is valid. Here it is:
[{"country":"UK","countryLongName":"United Kingdom","currency":"GBP"}]
[{"country":"UK","countryLongName":"United Kingdom","currency":"GBP"}]
我使用 https 在本地主机上运行,并且在我的清单(带和括号)中有以下 AppDomains:
I'm running on localhost with https, and have the following AppDomains in my manifest (belt and braces):
<AppDomain>https://localhost:44321/api/Country</AppDomain>
<AppDomain>https://localhost:44321</AppDomain>
<AppDomain>https://localhost</AppDomain>
但是,始终使用以下参数调用 getJSON.fail():
However, getJSON.fail() is always invoked, with the following parameters:
- xhr.responseJSON:未定义
- xhr.statusText:错误"
- 状态:错误"
- 错误:"
为什么 getJSON 总是失败?
Why does getJSON always fail?
进一步编辑我已经尝试过这个 js...
Further editI've tried this js instead...
$.ajax({
url: apiUrl,
dataType: 'json',
async: false,
data: params,
success: function (data) {
showNotification(data);
},
error: function (msg) {
showNotification('error : ' + msg.d);
}
});
...现在正在使用以下参数调用错误函数:
...and now the error function is being invoked with the following parameters:
- msg.responseJSON:未定义
- msg.status: 0
- msg.statusText:网络错误"
推荐答案
这一切都与 CORS 有关,我在 rick-strahl 的帖子中找到了解决方案:
It's all to do with CORS, I found the solution in rick-strahl's post:
https://weblog.west-wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas#ApplythePolicy
具体来说,必须在 UseMvc() 之前调用 UseCors()确保在 MVC 之前声明 CORS 功能,以便中间件在 MVC 管道获得控制权并终止请求之前触发."
Specifically,"UseCors() has to be called before UseMvc()Make sure you declare the CORS functionality before MVC so the middleware fires before the MVC pipeline gets control and terminates the request."
这篇关于为什么我的 jQuery getJSON 调用(在 Office.js(Excel js 加载项)中)返回错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!