首页 > 解决方案 > 将数据传递给 Web 服务获取 - 500(内部服务器错误)

问题描述

我在从 ReactJS 获取数据并将数据传递到 ASP.NET Web 服务时遇到问题。

仅在从数据库中获取数据时,其他 fetch 功能才起作用。为什么我会收到这些错误?我在这里做错了什么?signUp我相信它在我的fetch 功能中有所体现。

我认为该响应是 fetch 无法读取来自服务器的响应 -

main.chunk.js:2417 POST http://localhost:50496/WebService.asmx/SignUp 500 (Internal Server Error)
SyntaxError: Unexpected token T in JSON at position 0  at JSON.parse (<anonymous>)

反应JS

userData = {
    fName: 'some',
    lName: 'two one',
    email: 'someonw@gmail.com',
    password: 'se123456'  }

我在 ReactJs 中的 fetch 函数 -

   const signUp = (signUpData) => {
 
    let data = {
      firstName: signUpData.fName,
      lastName: signUpData.lName,
      emailAddress: signUpData.email,
      password: signUpData.password,
    };
    fetch('http://localhost:50496/WebService.asmx/SignUp', {
      body: JSON.stringify(data),
      method: 'POST',
      headers: {
        'Content-Type': 'application/json; charset=UTF-8',
      },
    })
      .then((response) => response.text())
      .then(
        (xml) =>
          new window.DOMParser().parseFromString(xml, 'text/xml')
            .documentElement.firstChild.textContent
      )
      .then((jsonStr) => JSON.parse(jsonStr))
      .then((userData) => {
        if (userData.d  && userData.d.length > 0) {
          setUser(userData);
        } else {
          console.log('error no data');
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

来自 Chrome 的错误 -

System.InvalidOperationException:缺少参数:firstName。System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection 集合) System.Web.Services.Protocols.UrlParameterReader.Read(HttpRequest request) System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() System.Web.Services.Protocols .WebServiceHandler.CoreProcessRequest()

SignUpWebMethod 在 WebService 中工作。

[WebMethod]
public string SignUp(string firstName, string lastName, string emailAddress, string password)
{
   return BLL.SignUp(firstName, lastName, emailAddress, password);
}

Chrome - 网络 - 标题

标签: asp.netreactjsweb-servicesfetchinternal-server-error

解决方案


我发现我需要做的,
另一个错误是 -

InvalidOperationException:只能从脚本中读取类定义中具有 [ScriptService] 属性的 Web 服务。

所以我在WebService.cs中添加了属性类[ScriptService]

 [WebService(Namespace = "http://tempuri.org/")]
 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 [ScriptService]

而且由于这完全消除了在使用标准 SOAP(简单对象访问协议)Web 服务时必须解析 XML 的需要,
所以我删除了这些代码行 -

.then((response) => response.text())
      .then(
        (xml) =>
          new window.DOMParser().parseFromString(xml, 'text/xml')
             .documentElement.firstChild.textContent 
      )
      .then((jsonStr) => JSON.parse(jsonStr))

并改为这个 -

 .then((response) => response.json())
  .then((userData) => {
    if (userData.d && userData.d.length > 0) {
      let user = JSON.parse(userData.d);
      setUserData(user);
      }

推荐阅读