gpt4 book ai didi

javascript - XMLHttpRequest URL 格式错误 - 错误 405

转载 作者:行者123 更新时间:2023-12-03 08:29:33 27 4
gpt4 key购买 nike

我将 XMLHttpRequest 发送到 Rest API 服务器,如下所示:

function sendPostRequest (accessToken)
{
// construct an HTTP request
var xhttp = new XMLHttpRequest();


//build data
var data = {};
data["accessToken"] = accessToken ;

xhttp.open("POST", "http://localhost:61103/api/Test", true);
xhttp.setRequestHeader('Content-Type', 'text/plain; charset=UTF-8');
xhttp.send(JSON.stringify(data));

xhttp.onloadend = function () {

};
}

这是由 ASP.NET Web API 接收的:

    [HttpPost]
public IHttpActionResult Post(string userToken)
{
//stuff
}

但是,我总是返回 405 错误。很可能是因为请求没有 Rest 参数(认为没有合适的重载),即看起来像这样:

POST http://localhost:61103/api/testAPI HTTP/1.1
Host: localhost:61103
Connection: keep-alive
Content-Length: 21
Origin: http://localhost:61103
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36
Content-Type: text/plain; charset=UTF-8
Accept: */*
Referer: http://localhost:61103/Testlogin.html
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

{"accessToken":"asd"}

请注意,数据不包含在链接中,而是包含在底部。

此外,这有效

xhttp.open("POST", "http://localhost:61103/api/Test?userToken=XXXX", true);

最佳答案

尝试添加可选参数

[HttpPost]
public IHttpActionResult Post(string userToken = "")
{
// base code off of param
}

这是基于此处的 ASP 文档:http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

For example, consider the following action:

public void Get(int id)

The id parameter binds to the URI. Therefore, this action can only match a URI that contains a value for "id", either in the route dictionary or in the query string.

Optional parameters are an exception, because they are optional. For an optional parameter, it's OK if the binding can't get the value from the URI.

所以我认为您要么需要编辑没有值的 ajax url,要么在服务器代码中使用可选参数。

如果不是,则可能是您的 IIS 配置,请参见此处:http://www.asp.net/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications

关于javascript - XMLHttpRequest URL 格式错误 - 错误 405,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33403519/

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