发送apiKey在html表单post或替代

Send apiKey on a html form post or alternative

本文关键字:post 表单 apiKey html 发送      更新时间:2023-09-26

我正在做一个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头,这是可能的形式?如果没有,还有什么其他选项,让我做一个跨域的帖子,当我按下一个按钮在我的asp.net MVC5页面?

谢谢

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

这些报头是响应报头,如果启用CORS,它们将从服务器返回。你不应该把它们发送到服务器。

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

所以,只要确保你的服务器返回Access-Control-Allow-Origin头。

你应该只发送你的自定义头(与API密钥)的方式(你在正确的方式):

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