【问题标题】:Send POST request to Rest WS with JS使用 JS 向 Rest WS 发送 POST 请求
【发布时间】:2012-03-30 20:18:13
【问题描述】:

我正在尝试使用 javascript 向 WCF 服务发送 REST 请求。 我已经使用.net 客户端尝试了该服务,它运行良好 这是我在 wcf 服务中的示例方法:

[OperationContract]
[WebInvoke(Method="POST", 
   ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
bool GuardarJuan(Persona persona);

从javascript我尝试了这些方法:

function sendRequest3(){
var datos='{"IdPersona":2,"Nombre":"David BQ"}';
var parameters = JSON.stringify(datos);
        var req=$.ajax({
            url: 'http://localhost:8732/Design_Time_Addresses/RestTEST/GuardarJuan',
            type: 'POST',
            data: parameters,
            contentType: 'application/json',
            dataType: 'jsonp'
        });
    }

还有这样的:

function sendPost(){
    var url = "http://localhost:8732/Design_Time_Addresses/RestTEST/GuardarJuan";
    var persona={
        IdPersona: 2,
        Nombre: 'David BQ'
    };
    var parameters = JSON.stringify(persona);
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/json");
    xmlHttp.send(parameters);
    xmlHttp.onreadystatechange= function X()
        {

             if(xmlHttp.readyState == 4)
             {
                  alert(xmlHttp.responseText);
             }
        }

但这些都不起作用。
它总是给我一个 405 错误 Method not allowed 或 0x80004005 (NS ERROR FAILURE)

谢谢

编辑: 问题解决了..这是跨域问题。 我是用 VS 服务器做的,所以我改用 IIS,一切正常

【问题讨论】:

  • 您排除了什么?谷歌搜索给了我social.msdn.microsoft.com/forums/en-US/wcf/thread/… 另外,您可能以某种方式禁用了 IIS 服务器上的 POST。
  • 我相信,如果您更改端口号,那么您将更改域并应用跨域策略,这意味着您必须为此请求使用 JSONP 或创建服务器端代理来获取JS 脚本的 JSON。

标签: javascript jquery wcf rest post


【解决方案1】:

首先,“服务”是否与您尝试与之通信的页面位于同一域中?

其次,如果您尝试使用 JSONP,则只能使用“GET”而不是“POST”,因为 JSONP 只是创建了一个

您可能需要使用 IIS/IISExpress 并在同一主机上安装主应用程序和 wcf 应用程序:端口。

【讨论】:

    猜你喜欢
    • 2021-05-08
    • 2015-09-25
    • 1970-01-01
    • 2013-02-25
    • 2021-07-15
    • 2020-10-05
    • 2019-04-26
    • 1970-01-01
    • 2019-03-29
    相关资源
    最近更新 更多