javascript - 如何将 curl 转换为 ajax?
问题描述
并尝试获取 API 密钥。该网站给了我一些卷曲代码。好吧,因为我是韩国人,不确定我是否理解了描述。无论如何,
curl --insecure -X POST
--header "Content-Type: application/x-www-form-urlencoded"
--header "Accept: application/json"
--data-urlencode "grant_type=urn:grant-type:apikey"
--data-urlencode "apikey=$API_KEY" "https://iam~~"
这是代码,我想知道在 ajax 调用代码上放置“--data-urlencode”部分的位置。
function to_ajax(){
$.getJSON("http://localhost~~/",
function(data){
$.ajax({
dataType: 'application/json',
data : {"grant_type":"urn:grant-type:apikey"
,"apikey=$API_KEY":"https://iam~~"},
headers: {"Content-Type" : "application/x-www-form-urlencoded" ,
"Accept": "application/json" } ,
success: function(msg) {
console.log(msg);
}
});
})
}
这是我到达的地方......耻辱......当我运行它时,我得到了CORS错误。IBM 解释说,API Gateway 可以运行 API CORS 操作来处理 API 的跨域资源共享 (CORS) 请求。
默认情况下,API 禁用 CORS,在这种情况下,API 网关将所有 CORS 请求传递到后端进行处理。当预检请求被传递到后端时,必须为每个可以成为请求目标的路径定义一个 OPTIONS 操作。否则,对该路径的预检请求可能会导致错误。
所以这意味着他们允许所有访问权限,对吗?
解决方案
对于 Ajax,3 个选项,我还添加了 ASP 答案,因为它出现在我的 ASP 搜索标签中!
- 将此添加到您的 Ajax 调用中的标题中。它仅限于一个站点,您可以使用 a
*
使其允许所有站点(不推荐)
headers: { 'Access-Control-Allow-Origin': 'http://The web site you are specially allowing to access' },
// 或使用 *
function to_ajax(){
$.getJSON("http://localhost~~/",
function(data){
$.ajax({
dataType: 'application/json',
data : {"grant_type":"urn:grant-type:apikey"
,"apikey=$API_KEY":"https://iam~~"},
headers: { 'Access-Control-Allow-Origin': 'http://TCUrl stack overflow' }, //only a specific site
headers: {'Access-Control-Allow-Origin': '*'}, //or allow everybody
headers: {"Content-Type" : "application/x-www-form-urlencoded" ,
"Accept": "application/json" } ,
success: function(msg) {
console.log(msg);
}
});
})
或与
Jsonp
// 如果其他服务器允许 JSONP $.ajax({ type: 'POST', crossDomain: true, dataType: 'jsonp', url: '', success: function(jsondata){
} })
您可以使用Ajax-cross-origin 一个 jQuery 插件。使用此插件,您可以使用
jQuery.ajax()
跨域。它使用谷歌服务来实现这一点:
AJAX Cross Origin 插件使用 Google Apps 脚本作为未实现 jSONP 的代理 jSON getter。当您将 crossOrigin 选项设置为 true 时,插件会将原始 url 替换为 Google Apps 脚本地址并将其作为编码的 url 参数发送。Google Apps 脚本使用 Google 服务器资源来获取远程数据,并将其作为 JSONP 返回给客户端。
易于使用以下插件:
$.ajax({
crossOrigin: true,
url: url,
success: function(data) {
console.log(data);
}
});
你可以在这里阅读更多: http ://www.ajax-cross-origin.com/
- 对于 ASP Web 应用程序,
web.config
请在您的内部添加以下 protocall选项以允许 CORS 调用。
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
推荐阅读
- android - 在芯片视图内添加一个圆形进度图标
- flutter - 如何在颤动中重叠视频文件上的文本或图像
- android - 如何使用导航组件创建固定快捷方式?
- snowflake-cloud-data-platform - 雪花日期范围查询历史数据并添加增量
- github - Github:选择所需的状态检查不适用于 Github 操作
- .net - WCF 服务方法调用了两次
- python - 计算名词和动词/形容词之间的共现
- parameters - 如何为 UML 类图中的参数指定条件?
- javascript - 我是初学者,面临 Javascript 和 html 链接的问题。在 HTML 中看不到 Javascript 的效果
- json - 使用嵌套 json 和受控组件反应表单