0

Backend code example: I am trying to get users here from my SQL Server database Account:

async function executeQuery() {
  try {
    const pool = await sql.connect(config);
    const result = await pool
      .request()
      .query(`USE Account SELECT TOP 10 UserNo FROM UserTable`);
    return result;
  } catch (err) {
    console.log(err);
  }
}

app.get("/api/data", async (req, res) => {
  const result = await executeQuery();
  res.json(result);
});

React frontend code: I am getting an error when try to render data from SQL Server.

import React, { useState, useEffect } from "react";

function SqlTest() {
  const [data, setData] = useState([]);

  async function fetchData() {
    const result = await fetch("/api/data").then((res) => res.json());
    setData(result);
  }

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

  return (
    <div>
      {data.map((item) => (
        <div key={item.UserNo}>{item.UserNo}</div>
      ))}
    </div>
  );
}

export default SqlTest;

I am trying to render data from SQL Server, but nothing helps..

enter image description here

2
  • Do you have 2 projects, one React and one NodeJS Express? Also, did you create this using CRA? Or Vite? Or something else? Commented Dec 28, 2022 at 5:04
  • Node js and react yes i used CRA Commented Dec 28, 2022 at 5:30

1 Answer 1

-1

Ok, your problem is a very common one that has a very common solution.

You have 2 separate projects (HTTP servers):

  1. The HTTP server that CRA comes with, which is a NodeJS server.
  2. Your API server, which happens to also be a NodeJS server.

Now you want to fetch data from React by querying your API server.

Look at your URL: api/data. This is a relative URL. Relative URL's are resolved by the browser by using the current page's domain. I don't know your exact setup, but the URL will end up being something like http://localhost:3000/api/data.

Do you see the problem already? Your API server is not listening on port 3000. It is probably listening on some other port number. After all, no 2 applications can listen on the same TCP port.

So you would then be tempted to change your fetch URL to a full URL that specifies the server API: http://localhost:3001/api/data. That probably works, but there's a chance it errors out due to CORS.

So long story short, do as the CRA help pages say you should do: Set a proxy up in your CRA server. Here it is: https://create-react-app.dev/docs/proxying-api-requests-in-development/

In a nutshell, create the file src/setupProxy.js with code similar to this:

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

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:5000', // <-- USE YOUR API PORT
      changeOrigin: true,
    })
  );
};

The sample assumes you're running your API server in port 5000. Change it to fit your configuration.

Sign up to request clarification or add additional context in comments.

3 Comments

testsql.js:7 GET http://localhost:3000/api/data net::ERR_CONNECTION_REFUSED fetchData @ testsql.js:7 getting now this
I don't know your port numbers. Use your port numbers. I don't have that information, you do.
i use 3000 for react and port 80 for node

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.