1

I figured out how to make a request to SQL server and post as JSON on the server side. I'm wondering how I can pull that data into the react side.

Server.js:

let pullTable = require('./actions/pullTable.js');
var express = require('express');
var app = express();

app.get('/', async (req, res, next) => {
  try {
    const result = await pullTable.pullTable();
    return res.status(200).json(result);
  } catch (error) {
    next(error);
  }
});

app.listen(5000, () => {console.log('Server is running..')});

SQL Request - pullTable.js:

var sql = require("mssql");
var express = require('express');
var app = express();
// config for your database
var config = {
    user: 'user',
    password: 'pass',
    server: 'localhost', 
    database: 'Master' 
};

const pullTable = async () => {
    try {
        const pool = await sql.connect(config);
        const sqlQuery = 'SELECT * FROM Persons';
        const result = await pool.request().query(sqlQuery);
        return result.recordset;
    } catch (err) {
        throw err;
    }
};

exports.pullTable = pullTable;

The code works fine up to here. I look at port 5000 and can see the JSON data being displayed from my server. Just not sure how to get this into React. This is my attempt at the react side (not including the App.js file - don't need help with that):

getData.js:

import React, { Component } from 'react';

class getData extends Component {
    constructor(){
        super();
        this.state={
            data:[],
        }
    }

    componentDidMount(){
        fetch('http://localhost:5000')
        .then((Response)=>Response.json())
        .then((findresponse)=>
        {
            this.setState({
                data:findresponse,
            });
        });
    }

    render() {
        return (
           <div>
                {
                    this.state.data.map((dynamicData)=>
                    <div>
                        <span>{dynamicData.LastName} </span>
                        <span>{dynamicData.FirstName}</span>
                    </div>
                    )
                }
            </div>
        );
    }
}

export default getData;

Just looking to display the first and last name of people in that SQL table.

3
  • What exactly is not working? Do you see any errors? Assuming the data you get from the server is something like [{ "Firstname": "John", "Lastname": "Doe" }, ... ], you should see the list of records from the database. Commented Apr 18, 2019 at 20:17
  • Did you check if the request was fired in the network tab of your browser dev tools? Was it a successful or failed request? Might be having issues with CORS. Commented Apr 18, 2019 at 20:25
  • The JSON is good, because when I put it into a local folder on my computer it reads it just fine. This is the error I'm getting in the console: "Access to fetch at 'localhost:5000' from origin 'localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled." Looks like it is a CORS issue. Any idea how to fix it? Thanks! Commented Apr 19, 2019 at 10:00

1 Answer 1

1

@Shawn Yap pointed me in the right direction. Basically had to include the Access-Control-Allow-Origin header on the server script:

let pullTable = require('./actions/pullTable.js');
var express = require('express');
var app = express();

app.get('/', async (req, res, next) => {
    try {
    res.set('Access-Control-Allow-Origin', '*');
    const result = await pullTable.pullTable();
    return res.status(200).json(result);
    } catch (error) {
    next(error);
    }
});

app.listen(5000, () => {console.log('Server is running..')});

Not sure if this even good code, but it's working.

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

Comments

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.