reactjs 与核心 3.1 api 控制器获取json错误而不是返回数据

如何解决reactjs 与核心 3.1 api 控制器获取json错误而不是返回数据?

我正在创建一个登录表单并尝试为会话状态取回数据。我收到错误“Uncaught (in promise) SyntaxError: Unexpected token

Login.js file

        import React,{ Component } from 'react';
        import { Header } from './Header';
    
        class Login extends Component {
            constructor(props) {
                super(props);
    
                this.state = { fields: { "idAccount": 0,"idAccountUser": 0,"UserFirstName": "","UserLastName": "","UserEmail": "","UserCulture": "","AllowContentdistribution": false },errors: {} };
                this.state = { inputFields: { "userName": "","password": "" } };
    
            }
    
        authenticateUser(e) {
            e.preventDefault();
            var userName = e.userName;
            var password = e.password;
    
            if (this.handleValidation()) {
    
                fetch("Http://localhost:1234/api/CustomerManager/AuthenticateUser?UserName=" + userName + 
        "&Password=" + password,{
                    method: "GET",headers: {
                        contentType: "application/json; charset=utf-8",accept: 'application/json'
                    },})
                    .then((response) => {
                        response.json();
                    })
                    .then((data) => {
                        this.state.fields = data;
                        console.log(data);
                        console.log("idAccount: {0},UserFirstName: {1},UserLastName: {2}",this.state.fields["idAccount"],this.state.fields["UserFirstName"],this.state.fields["UserLastName"]);
                    })
                    .catch((error) => {
                        console.log('error: ' + error);
                    });
            }
            else {
                console.log('error: ' + this.state.errors);
            }
        };
    
        handleValidation() {
            let fields = this.state.inputFields;
            let errors = {};
            let formIsValid = true;
    
            //UserName
            if (!fields["userName"]) {
                formIsValid = false;
                errors["userName"] = "UserName Cannot be empty";
            }
    
            //Password
            if (!fields["password"]) {
                formIsValid = false;
                errors["password"] = "Password Cannot be empty";
            }
    
            this.setState({ errors: errors });
            return formIsValid;
        };
    
         handleChange(field,e) {
            let fields = this.state.inputFields;
            fields[field] = e.target.value;
            this.setState({ fields });
        };
    
            render() {
            
                return (
                    <>
                        <Header />
                    <div className="login center">
                        <form
                                onSubmit={this.authenticateUser.bind(this)}
                        >
                            <div>
                                <label htmlFor="userName">
                                Username:
                            
                                </label>
                            </div>
                            <div>
                                <input
                                        id="userName"
                                        onChange={this.handleChange.bind(this,"userName")} value= 
       {this.state.inputFields["userName"]}
                                />
                            </div>
                            <div>
                                <label htmlFor="password">
                                Password (case-sensitive):
                            
                                </label>
                            </div>
                            <div>
                                <input
                                    id="password"
                                        type="password"
                                        onChange={this.handleChange.bind(this,"password")} value= 
       {this.state.inputFields["password"]}
                                />
                            </div>
                            <div>
                                <button className="Button ActionButton">Sign In</button>
                            </div>
                        </form>
                        </div>
                        </>
                );
            };
        }
    
        export default Login

Controller

    

    [HttpGet]
            public IHttpActionResult AuthenticateUser(string userName,string password)
            {
                try
                {
                    Login.AuthenticateUser(userName,password);
    
                    SessionState sessionState = new SessionState
                    {
                        IdAccount = IdAccount,IdAccountUser = IdAccountUser,UserFirstName = UserFirstName,UserLastName = UserLastName,UserEmail = UserEmail,UserCulture = UserCulture,};
    
                    return Ok(sessionState);
                }
                catch (Exception ex)
                {
                    // show the error
                    return InternalServerError(ex);
                }
    
            }

解决方法

基本上,问题出在响应类型上,我在我身边测试过,id确实有效。您的 login.js 中存在一些错误,但与您的错误无关。

根据我的搜索,我发现 IHttpActionResult 是一个不是 existed in Core 的接口,如果您的 web api 项目在 asp.net core 中,您需要使用 IActionResult。我还建议使用 asp.net core 而不是 asp.net。顺便说一句,如果仍然无法得到json响应,您可以参考this section在您的方法中添加过滤器[Produces("application/json")]

登录.js

import React,{ Component } from 'react';

class Login extends Component {
    constructor(props) {
        super(props);

        this.state = { fields: { "idAccount": 0,"idAccountUser": 0,"UserFirstName": "","UserLastName": "","UserEmail": "","UserCulture": "","AllowContentDistribution": false 
                            },errors: {},inputFields: { "userName": "","password": "" } 
                    };
    }

authenticateUser(e) {
    e.preventDefault();
    var userName = this.state.inputFields.userName;
    var password = this.state.inputFields.password;

    const res = fetch("https://localhost:44325/api/CustomerManager/AuthenticateUser?UserName=" + userName + "&Password=" + password,{
        method: "GET",headers: {
            contentType: "application/json; charset=utf-8",accept: 'application/json'
        },})
    .then(res =>res.json())
    .then((data) => {
        console.log(data);
        console.log("msg is :"+data.msg);
    })
    .catch((error) => {
        console.log('error: ' + error);
    });
};

handleChange(field,e) {
    let fields = this.state.inputFields;
    fields[field] = e.target.value;
    this.setState({ fields });
};

    render() {
    
        return (
            <>
                {/* <Header /> */}
            <div className="login center">
                <form
                        onSubmit={this.authenticateUser.bind(this)}
                >
                    <div>
                        <label htmlFor="userName">
                        Username:
                    
                        </label>
                    </div>
                    <div>
                        <input
                                id="userName"
                                onChange={this.handleChange.bind(this,"userName")} value= 
{this.state.inputFields["userName"]}
                        />
                    </div>
                    <div>
                        <label htmlFor="password">
                        Password (case-sensitive):
                    
                        </label>
                    </div>
                    <div>
                        <input
                            id="password"
                                type="password"
                                onChange={this.handleChange.bind(this,"password")} value= 
{this.state.inputFields["password"]}
                        />
                    </div>
                    <div>
                        <button className="Button ActionButton">Sign In</button>
                    </div>
                </form>
                </div>
                </>
        );
    };
}
export default Login

这是我的控制器,在 asp.net core3.1 中:

using Microsoft.AspNetCore.Mvc;

namespace test0715.Controllers
{
    public class AuthController : Controller
    {
        [Route("/api/CustomerManager/AuthenticateUser")]
        public IActionResult Index(string UserName,string Password)
        {
            SessionState ss = new SessionState
            {
                age = 18,name = "test"
            };
            return Ok(ss);
        }
    }

    public class SessionState {
        public int age { get; set; }
        public string name { get; set; }
    }
}

如果您在 asp.net 中编写 api,您可以看到下面的示例。在这里,如果我调用http://localhost:53148/api/auth?name=aa&psd=bb,我会得到xml响应,而我在login.js中调用它,我会得到json响应。

using System.Web.Http;
using System.Web.Http.Cors;

namespace WebApplication1.Controllers
{
    [EnableCors(origins: "*",headers: "*",methods: "*")]
    public class AuthController : ApiController
    {
        [HttpGet]
        public IHttpActionResult Get(string name,string psd)
        {
            Product product = new Product
            {
                age = 18,name = "hello"
            };
            return Ok(product);  // Returns an OkNegotiatedContentResult
        }
    }

    public class Product {
        public int age { get; set; }
        public string name { get; set; }
    }
}

App_start->webapiconfig.cs

using System.Web.Http;

namespace WebApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.EnableCors();
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

其他编程问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?