[HPM] An error was encountered while attempting to proxy the request for the website

My first project, but the backend data isn't coming from port 3000. I'm a bit lost and would really appreciate any help.

Springboot TestController

package com.example.joyit;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/api/test")
    public String text(){
        return "test api";
    }
}

App.js

import React, {useState,useEffect} from 'react';
import axios from 'axios'
import './App.css';

function App() {
  const [testStr, setTestStr] =useState('');

  function callback(str){
    setTestStr(str);
  }
  useEffect(
    ()=>{
      axios.get('/api/test')
      .then((Response)=>{callback(Response.data)})
      .catch((Error)=>{console.log(Error)})
    }, []
  );

  return (
    <div className="App">
      <header className="App-header">
        
        api/test =={'>'}
          {testStr}
        
      </header>
    </div>
  );
}

export default App;

setupProxy.js

const{createProxyMiddleware} = require('http-proxy-middleware');

module.exports = function (app){
    app.use(
        '/api',
        createProxyMiddleware({
            target:'http://127.0.0.1:8080',
            changeOrigin:true,
        })
    );
};

https://i.sstatic.net/r82z5.png

The backend data seems to be stuck. Any ideas on how to fix this?

If you could provide some guidance, I'd be really grateful.

Answer №1

If you're working with axios in reactjs, it's recommended to utilize a service class for making API calls.


class ApiService{
async getData(){
    const response = await axios.get('/api/test')
    return response;
  }
}

This way, you can easily reuse it in different components using tryCatch statements.

const fetchData = async() => {
       try {
            const response =await apiService.getData()
            setTestStr(response.data)
        } catch (error) {
          toast.error(error.response.data)
        }

}

 useEffect(() => {
        fetchData()
    }, [])

Furthermore, if you are working with SpringBoot, you can leverage the ResponseEntity Class to send back the response body.

    @GetMapping("/api/test")
    public ResponseEntity<String> text(){
        return new ResponseEntity("test api",HttpStatus.Ok);
    }

Lastly, when dealing with SpringSecurity, ensure that the method has the necessary permission for access.

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

Exploring through a table using JavaScript

I am struggling to search a table within my HTML for a specific term. The code I have works to an extent, but it does not account for alternatives such as searching for "what is that" when I type in "What is that". Additionally, I need the script to ignor ...

Retrieve data from MongoDB that is within the past week in ISO string format

My goal is to retrieve data from MongoDB that is exactly a week old. The specific field I am focusing on is - { _id:821398723913, closed_at:"2020-06-10T01:43:59-04:00" } I am looking to fetch all objects where the 'closed_at' field falls wit ...

Rendering elements dynamically using ng-repeat following an AJAX request

Feeling frustrated, I made an $http request ApiService.get_request_params("api/endpoint").then( function(data) { $scope.customers = data }, function(err) { } ); The $scope.customers should be bound to an ng-repeat. I can see the ...

What is the best way to prevent executing a method in [queryParams] in Angular 7?

I'm currently working on incorporating the option for users to open a link in a new tab. I'm trying to avoid using the (click) method, so I've come up with the following logic to achieve this: <a [routerLink]="['/search/' + sea ...

Retrieving error messages and status codes using Laravel and JWT authentication

One of the challenges I'm facing is implementing JWT Auth in my Laravel + Vue SPA. When checking the credentials in my Controller, the code looks like this: try { if (!$token = JWTAuth::attempt($credentials)) { return response()- ...

When the tooltip component is triggered in a React application, the cursor is automatically directed to

I have been working on creating an input field that allows users to enter time as input. Here's the code snippet I am using: <InputMask mask="99:99" onBlur={handleOnBlur} onChange={(e) => { const ...

Display the JSON data in a table only if the ID is a match

I am working on a table that consists of 5 rows and 2 columns. Each row is assigned an ID ranging from 1 to 5. My goal is to insert JSON data into the table, but only if the ID in the data matches the ID of the corresponding row. If there is no matching I ...

Creating a function with a flexible number of parameters assigned to a variable:

When setting up a Socket.IO client, I have multiple methods structured like the following: myobject.prototype.A = function (callback) { this.foo('a', null, callback); } myobject.prototype.B = function (bar, callback) { this.foo('b&a ...

Troubleshooting a malfunctioning custom filter in AngularJS

I'm having trouble implementing a custom filter in AngularJS. The output is not what I expected. Here is the code I have: script.js var myApp = angular.module('myModule', []); myApp.filter("gender", function(){ return function(gender){ ...

What is the best way to start data in an Angular service?

I'm currently navigating my way through building my first Angular application. One of the services I am using needs to be initialized with a schema defined in its constant block, but the schema/configuration is not yet finalized. Therefore, I am perfo ...

Using Webpack to Compile Sass (and keep class names local)

It's been a long journey trying to configure my Webpack setup to compile Sass, and the process has become quite overwhelming. In my quest for answers, I encountered numerous Github issues, Stackoverflow threads, and blog posts discussing how to integr ...

Using React Bootstrap, you can ensure that only a single collapse opens at a time when rendering it with a map function. This allows you to display

When a user clicks on the "View Tasks" button, I want to display the relevant tasks specific to that user. However, currently all React Bootstrap Collapse Components open up and show tasks for every user instead of just one. This issue arises because the o ...

Exploring the assortment of reactions post-awaitReaction in node.js

The current code runs smoothly, but I encounter an issue when attempting to send messages after selecting either the X or check option. Instead of the expected outcome, I receive Despite my understanding that this collection is a map, all attempts to acce ...

Can you explain the inner workings of the sort function mechanism?

After reading through this article about Array.prototype.sort(), I noticed that the Sort() function can behave differently depending on the availability of compareFunction. When it comes to sorting strings, it uses UNICODE values. However, in a specific ...

What could be causing the slow build time for npm run serve on a Vue.js project?

My Vue.js project was running smoothly until about an hour ago when I noticed that it is now taking a very long time to build. Specifically, it gets stuck at 32% for more than 5 minutes. Does anyone have any suggestions on how to fix this issue? I'm n ...

Attempting to duplicate Codepen's code onto my local machine

Trying to figure out how to make this work locally after finding it on codepen https://codepen.io/oxla/pen/awmMYY Seems like everything works except for the functionality part. I've included the JS File and the latest Jquery in my code. <head&g ...

Utilizing Jquery for ASP.NET, an AJAX call dynamically populates a list

My user interface is designed to populate a select dropdown menu using data retrieved from a database through an AJAX call. The C# web method responsible for this operation is structured as follows: private static List<List<string>> componentT ...

Tips for verifying a list of objects within a request body with JOI

I'm in the process of validating the request body for an order placement. The request body contains an array of JSON objects that I need to validate, but I keep encountering the error message "productId" is required. Below is the structure of my requ ...

Utilizing jQuery to eliminate a script function from an external webpage

Currently, I am utilizing a ColdFusion script to load an external page within the container tag. This external page contains a sorting function defined as: function sorting(sortid). However, this function's sorting criteria constantly leads to errors ...

converting values to hexadecimal for array transmission in JavaScript

Looking to insert a hexadecimal value into an array in order to write to a device via modbus/TCP using socket communication. Currently facing an issue where I am unable to retrieve the hex value with the same data type as the elements present in byteArrayW ...