javascript - 通过 html 表单帖子或其他方式发送 apiKey

标签 javascript jquery html asp.net asp.net-mvc

我正在做一个 ASP.NET mvc5 项目。 在其中一个页面中,我有一个按钮,我想用它来向跨域 api 发送帖子。

我尝试过使用 ajax 来完成这样的帖子:

      $.ajax({
        type: "POST",
        url: URLX,
        data: myJSObject,

        success: function (data) {
            console.log("test123");
        },
        "async": true,
        "crossDomain": true,
        headers: {
            "Content-Type": "application/json",
            //"Authorization": "Bearer XX+n06LhXHb/cAZyBSvXZAd1LlkO8NqtORuHGyexWr4=",
            "apiKey": "MEV8yv3hxxxxxxxxxxxxxxxFdKWJer4H3LmL6ntcL",
            "Access-Control-Allow-Headers": "*",
            "Access-Control-Allow-Origin": "*"
        }

    });

但是从我读到的内容来看,我无法使用 JavaScript 进行跨域请求,所以我尝试使用表单:

<div class="hiddenform">
<iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>
<form action="http//something.com/otherthing" id="login_form" method="post" target="hiddenFrame">
    <div class="form_section">You can login here</div>
    <div class="form_section">
        <input xmlns="http://www.w3.org/1999/xhtml" class="text" id="userIdform"
               name="session[sec1]" tabindex="1" type="text" value="" />
    </div>
    <div class="form_section">
        <input xmlns="http://www.w3.org/1999/xhtml" class="text" id="periodform"
               name="session[sec2]" tabindex="1" type="text" value="" />
    </div>
    <div class="form_section">
        <input xmlns="http://www.w3.org/1999/xhtml" class="text" id="benchform"
               name="session[sec3]" tabindex="1" type="text" value="" />
    </div>
    <div class="form_section">etc</div>
    <div xmlns="http://www.w3.org/1999/xhtml" class="buttons">
        <button type="submit" class="" name="" id="goform" tabindex="3">Go</button>

    </div>
</form>

此外,这是服务器 CORS 配置 https://gist.github.com/michiel/1064640

我的问题是我需要发送带有 apiKey 的 header ,这可以在表单中吗?如果没有,还有什么其他选项可以让我在按下 ASP.NET MVC5 页面上的按钮时进行跨域发布?

谢谢

最佳答案

可以使用跨域XMLHttpRequest CORS如果您的端点支持。

这些 header 是响应 header ,如果启用了 CORS,它们将从服务器返回。您不应该将它们发送到服务器。

    "Access-Control-Allow-Headers": "X-Requested-With",
    "Access-Control-Allow-Origin" : "*"

因此,只需确保您的服务器返回 Access-Control-Allow-Origin header 即可。

您应该仅以这种方式发送自定义 header (带有 API key )(您的方向是正确的):

$.ajax({
    ...
    headers: { 'APIKeyPost': 'MEVxxxxxxxxxxxxxx4H3LmL6ntcL' }
    ...
});

关于javascript - 通过 html 表单帖子或其他方式发送 apiKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32455613/

相关文章:

javascript - bootstrap modal $(...).modal 不是一个函数

javascript - 如何在 jQuery 中将可点击图像定位到浏览器顶部

html - 我可以直接在 html 页面中进行 XSLT 转换吗?

javascript - 如何通过网站链接打开手机上的应用程序

javascript - 在jsp中访问javascript中的 session 变量

javascript - 在ZK中处理MouseScroll

javascript - AJAX仅发送一次post请求

html - 如何使用滚动条在一行上生成大量堆叠的 div

javascript - 有人可以向我解释一下这个 JS 代码和错误吗?为什么会失败?

javascript - 如何创建一个播放 mp3 google tts 的按钮