Fetiching ReactJS with Asp Net core

I am trying to get Data from Asp net core to be passed into Reactjs.
I have looked into a couple of projects but it is confusing to try to learn everything at once
I would Just like to learn the basics of connecting Reactjs with asp net core Like getting a single string data from asp net core to be passed into Reactjs and to pass a string or
a int from a ReactJs Input and let asp net core do something with it

So This is my ReactJs Code:

import React, { Component } from 'react';

export class New extends Component {
    static displayname = New.name;

    constructor(props) {
        super(props);
        this.state = {
            Names1 : "nothing"
        };
    }
    componentDidMount() {
        fetch("https://localhost:44311/reacttest/Names").then(res => res.json()).then(
            result => { this.setState({ Name1: reacttest.Names }) })
    }
    render() {
        return (
            <h1>my name = {this.state.Names1} </h1>
            )
    }

    async getnames() {
        const response = await fetch('Names');
        const data = await response.json();
        this.setState({ Name1: data})
    }
}

this is my Asp Net Core Model:

public class Names
	{

		public string NewName { get; set; }
	
	}

my controller:

	public static void getnames()
		{
			Names myobj = new Names();
			myobj.NewName = "ANewName";		
		} 

I am not really sure what I am doing here
please help me out

I haven’t done asp.net before, but in general it shouldn’t matter - an endpoint is an endpoint. You can write it in any language and your frontend doesn’t care.

So, you have two problems: 1) Getting a working endpoint, and 2) Accessing that endpoint.

Can you hit that endpoint. Can you put that url into an address bar and get the data back? Or maybe with Postman?

And then once you have a working endpoint, what are you getting in the frontend app? What is the network tab telling you? Can you log out res and result so we can see what those are? Also, what is reacttest.Names. Is reacttest defined anywhere? If it is undefined, then that could be causing your app to crash.

Thank you for your response,
I have tried something different now but it is still not working:

import { data } from 'jquery';
import React, { Component } from 'react';

export class New extends Component {
    static displayname = New.name;

    constructor(props) {
        super(props);
        this.state = {
            Names1 : "nothing"
        };
    }
    componentDidMount() {
        fetch('reacttest/TestingController/New')
            .then(Response => (Response.json())
            .then(data => { this.setState({ Name1: data }) })
    }

    render() {
        return (
            <h1>my name = {this.state.Names1} </h1>
            )
    }
}

and asp net core Controller:

namespace reacttest.Controllers
{

	public class TestingController : Controller
	{
		[HttpGet("New")]
		public string New()
		{
			string Name = "Jon";
			return Name;
		}
	}
}

I think the urls are matching up now but i do not understand the fetch part

OK, I asked a few questions which you haven’t answered:

  1. Can you hit the endpoint in your browser or Postman?
  2. After that, what do you see in your network tab of your devtools?
  3. What do you get if you log out res and result?

Also, to your fetch, I’d add a catch block so we can catch any errors:

        fetch('reacttest/TestingController/New')
            .then(Response => (Response.json())
            .then(data => { this.setState({ Name1: data }) })
            .catch(err => console.log('Fetch error:', err))

I’m sorry

  1. Im not familiar with the term endpoint but i am able to reach the url “reacttest/TestingController/New” if that is what you mean. I have never worked with Postman.

  2. When inspect the elements with google chrome:

<div class="container"><h1>my name = nothing </h1></div>

Using your catch code .The error message I see in the console = " SyntaxError: Unexpected token < in JSON at position 0 "

the page itself is showing no errors and it returns “Nothing” as the value of Names1

3.Im sorry I dont understand what you mean with “log out res and result” the page has no authentication there is no login or logout system.

I’m sorry if i dont understand you correctly I am new to this.

I’m sorry if i dont understand you correctly I am new to this.

Don’w worry, we were all there once.

Im not familiar with the term endpoint but i am able to reach the url “reacttest/TestingController/New” if that is what you mean.

Right, the “endpoint” or the “API endpoint” or the “web service endpoint” is just the address that allows access to a server. In your initial example, “https://localhost:44311/reacttest/Names” is the endpoint (I’m fudging a little here but that’s the basic idea). It is an address that your app uses to find a “window” or “mailbox” with with which it can talk with the server. The server creates those endpoints and listens to them for when a frontend (client) app calls them.

If you are doing a simple GET and there is not auth to worry about, etc. - you can usually just cut and paste that URL into address bar of your browser and it will hit that endpoint with a GET and show the results in the browser window. That is an easy way to see if the endpoint is live.

I have never worked with Postman.

Postman is a tool you can use on your computer. While the above method will do simple GETs, using Postman you can do all sorts of calls to your endpoint and monitor what is happening.

  1. When inspect the elements with google chrome:

That doesn’t really help us. I was suggesting looking at the network tab in your dev tools. With that you could watch the actual API call to that endpoint, see what it is sending and what it is getting back.

Im sorry I dont understand what you mean with “log out res and result” the page has no authentication there is no login or logout system.

When I said “log out”, in this sense I mean "send data to the console using console.log. I was suggesting something like this:

        fetch('reacttest/TestingController/New')
            .then(Response => {
              console.log('Response', Response)
              return Response.json()
            })
            .then(data => {
              console.log('data', data)
              this.setState({ Name1: data })
            })
            .catch(err => console.log('Fetch error:', err))

Using your catch code .The error message I see in the console = " SyntaxError: Unexpected token < in JSON at position 0 "

OK, that is useful. That is saying that the call to Response.json() is “throwing” an error. When an error is “thrown”, it skips all the remaining code in the then chain and skips straight to catch.

So, this happens when that json method tries to parse something that isn’t valid JSON. What is it? Well, that’s where those console.log statements, checking the network tab, using Postman, or trying out the endpoint address in the browser would have helped. However, we can glean a few things. First, “<” is not a valid JSON character so JSON cannot start with it, ever - whatever it is sending back, it isn’t JSON. Furthermore, in my experience, this indicates that the endpoint failed and is sending back an error web page. We can find out for sure what is happening by checking the network tab, etc.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.