C# backend and React frontend struggling with MVC routing implementation

Exploring MVC with .Net for the first time. Here is my C# controller implementation:

namespace TFL.Controllers
{
    [Route("api/[controller]")]
    public class TubeApiController : Controller
    {
        [HttpGet("[action]")]
        public async Task<IActionResult> GetTubeStatus()
        {
            using (var client = new HttpClient())
            {
                try
                {
                    client.BaseAddress = new Uri("https://api.tfl.gov.uk");
                    var response = await client.GetAsync("/Line/Mode/tube/Status");
                    response.EnsureSuccessStatusCode();

                    var stringResult = await response.Content.ReadAsStringAsync();

                    var rawData = JsonConvert.DeserializeObject<List<RootObject>>(stringResult);

                        return Ok(new
                        {
                            LineId = rawData[0].name
                        });

                }
                catch (HttpRequestException httpRequestException)
                {
                    return BadRequest("Error getting data");
                }
            }
        }

    }


    public class RootObject
    {
        [JsonProperty("name")]
        public string name { get; set; }
        public List<LineStatus> lineStatuses { get; set; }

    }

    public class LineStatus
    {
        public string statusSeverityDescription { get; set; }

    }

}

My goal is to fetch this data and display it on the front end:

import React, { Component } from "react";


export class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            lineId: "",
            status: ""
        };
    }

    getData(e) {
        e.preventDefault();
        fetch("api/tubeapi/gettubestatus")
            .then(res => res.text())
            .then(text => console.log(text))

    }

    render() {

        return (
            <div>
                <center>
                    <h1>Tube</h1>
                    <h4>Name</h4>
                    <p>{this.state.lineId}</p>
                    <h4>Status</h4>
                    <p>{this.state.status}</p>

                </center>
            </div>
        );
    }
}

When I visit localhost:5000/api/tubeapi/gettubestatus I receive the expected JSON response: {lineId: "Bakerloo" }(which is what I need for practice), however, the code does not fetch this data as intended. I've tried to debug by logging the text fetched by the API call but nothing shows up in the console. Any suggestions on where I might be going wrong would be greatly appreciated. Thanks

**Edit: my package.json file for one of the comments: **

{
  "name": "tfl",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "babel-eslint": "10.0.1",
    "bootstrap": "^4.1.3",
    "jquery": "^3.4.1",
    "merge": "^1.2.1",
    "oidc-client": "^1.9.0",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "react-router-bootstrap": "^0.24.4",
    "react-router-dom": "^4.2.2",
    "react-scripts": "^3.0.1",
    "reactstrap": "^6.3.0",
    "rimraf": "^2.6.2"
  },
  "devDependencies": {
    "ajv": "^6.9.1",
    "cross-env": "^5.2.0",
    "eslint": "^5.12.0",
    "eslint-config-react-app": "^4.0.1",
    "eslint-plugin-flowtype": "^2.0.0",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-react": "^7.11.1",
    "typescript": "^3.5.2"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "scripts": {
    "start": "rimraf ./build && react-scripts start",
    "build": "react-scripts build",
    "test": "cross-env CI=true react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "lint": "eslint ./src/"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Answer №1

It seems like the issue is related to not specifying the absolute URL and instead using a relative URL. To resolve this, you need to indicate the port on which your backend server is running.

Since your .net application server is running on port 5000, you should specify this in the package.json file of your React application to use the relative URL correctly.

To do so, add the following line to your package.json under browser list and restart your app. Remember that any changes made in the package.json file require a restart for the updates to take effect:

"proxy": "http://localhost:5000"

In your code, when using

fetch("api/tubeapi/gettubestatus")
, make sure to include it as described above and check if you can now see the response.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Have you ever wondered about the magic that unfolds when we utilize AJAX

I'm confused about the concept of AJAX. When we use AJAX, why doesn't the page get refreshed every time? Is this related to the page_load method or something else? ...

I'm sorry, but we were unable to locate the module: Error: Unable to find 'fs' in '/usr/src/app/node_modules/jpeg-exif/lib'

Encountering an error when building a react app on production: Module not found: Error: Can't resolve 'fs' in '/usr/src/app/node_modules/jpeg-exif/lib' Node Version: Node version 18 Steps taken in Docker Production: npm install - ...

When using React Material UI Table to spread a detail line over 2 rows, a warning may appear: "Warning: Each child in a list should have a unique 'key' prop."

I am working on formatting my table in a specific way: EVENT ID EVENT NAME DATE LOCATION 12345678 Rolling Stones 01/01/2024 Merriweather Post Pavillion Rain or shine! No weapons or alcohol will be permitted 1234567 ...

How to add to the existing route without replacing in React Router?

Is there a way to append to the route using react router without specifying the complete path? Imagine the current route is /page1/page2 and I want to navigate to /page1/page2/next-page To achieve this, first I need to access the router const router = us ...

Is there a way to include personalized text in react-datepicker?

I am facing an issue with adding "from" (date) to a react-datepicker input, as it is displaying strange behavior. Here is my code : const [ data, setData ] = useState({ startDate: new Date(), endDate: new Date() }) const handleChange ...

Error TRPCClient: The unexpected presence of the token "'<'", ""<!DOCTYPE "... invalidates the JSON format within Next.JS

Encountering an error in the authentication call back page: TRPCClientError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON in Next.JS. The issue occurs in src/app/auth-callback/page.tsx and here's the relevant code ...

Positioning a badge on a List in Material UI when there are no children

I need assistance creating a ListItem within a List that includes text and a badge counter on the right-hand side. import React from "react"; import { Badge, Card, List, ListItem, ListItemButton, ListItemText, } from "@material-u ...

Implementing Winston logging into a React JS project

I am looking to integrate Winston logging into my React application that was created using create-react-app. First, I installed Winston by running the following command: npm install winston Next, I imported Winston into my app.js file like so: import win ...

Encountering an unusual hash code when implementing Google Tag Manager in a Next.js project was

I am currently using Next.js and have added Google Tag Manager through a script <script dangerouslySetInnerHTML={{ __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var ...

how to share global variables across all components in react js

Operating a shopping cart website requires transmitting values to all components. For instance, when a user logs into the site, I save their information in localStorage. Now, most components need access to this data. My dilemma is whether I should retriev ...

Enabling communication between directives using controller API in AngularJS

Interaction Between Child and Parent Directives While the code below generally functions properly, there is an issue that arises when the template line in the parent directive (parentD) is uncommented: .directive('parentD', ['$window', ...

Creating a portal in React.js can be achieved by utilizing the createPortal method from ReactDOM. This process involves transforming code from

Currently, I am in the process of converting my next.js code to react.js and I have encountered a new challenge. I am using portal for the first time and require some assistance on where exactly I should place the <div id="photo-picker">< ...

React Native's fetch function appears to be non-responsive

I am experiencing an issue where the fetch function does not seem to fire in my React Native component: import { Button } from 'react-native'; export function Test() { function submit() { console.log('submit'); fetch('h ...

Ensure the function has completed setting state before proceeding to the next function

async componentDidMount() { this.loadSelectors(); this.useSelectors(); }; loadSelectors = () => { this.setState({"Selector": "Test"}); } useSelectors = () => { console.log(this.state.Selector); } Is there a way to ensure that loadS ...

When utilizing React-Router within Express on my local environment, why is my HTML root appearing blank?

I currently have two routes '/' and 'login' that I am trying to set up on the same page. However, when I load the page through express instead of webpack-dev-server, I only see a blank html page rather than the react-router loading corr ...

What could be causing the issue with HTML not being printed upon button click in ReactJS?

My goal is to display the word "Hello" on the screen when the add button is clicked. However, I am encountering an issue where it is not showing up. Any insights or solutions would be greatly appreciated! import React, { Component } from 'react'; ...

Customize Material-UI FAB Hover Color

While working on my project, I encountered an issue with a floating action button that contains an SVG icon nested underneath it. Even though the SVG icon is not in the children prop of the FAB, hovering over the FAB or the SVG icon causes the FAB to chang ...

Is there a way to transfer the data from a chosen row into a different table?

My task involves using a table with two different conditions. In the first table, I display all incoming data. Then, in the second table (referred to as "select summary"), I want to show the row selected in the first table. To achieve this, I am utilizing ...

Error: Module 'config' not found by Jest

I have encountered an issue while using Jest to test my api calls file. When running a simple test, I received an error Cannot find module 'config' from 'api.service.js'. This error is related to the import statement at the top of my ap ...

What is the process for transforming a String into an HTML element within a Next JS Application?

I stored the product description as HTML elements in a Database, but when I try to render this data into a div, it displays as a String. I am looking to showcase all the data as HTML elements in my Next JS application. I attempted using JSON.parse, but unf ...