0

I'm trying to retrieve data from a SQL database and display that said data on a Reactjs web app. However, all the calls I make to the database results in the HTML of the webpage in focus. I have set the headers, and I've tried to change the way the response from the express call is being handled.

Here is the expressjs script I am using right now:

const express = require('express');
const sql = require('mssql/msnodesqlv8');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const db = require('./db.js');

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/counselling/triageadmin/', express.static(path.join(__dirname, '/build')));
app.use(cors());

app.get('/getTable', function (req, res, next){
    var request = new sql.Request(db);
    request.query('select * from Counselling order by TicketID desc', (err, result) =>{
        if (err) { return next(err); }
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify(result["recordset"]));
    });
});

From there, my axios calls look like this:

componentWillMount(){
  let self = this;
  axios.get("/getTable")
  .then(function (response){
    console.log(response.data);
    self.setState({
      data: response.data,
    });
  })
  .catch(function (error){
      console.log(error);
  })
}

I added the console.log to check what was being returned, and as said, it was the HTML code of the current page of focus.

I made some changes to reflect what steps I took to get the 500 issue out. The current code, however, results in a 404.

Andy Wong
  • 73
  • 2
  • 12
  • What does the HTML actually say? perhaps it is reporting a 505 error or some other error. – Octopus May 31 '17 at 15:56
  • It's actually not an error, the get request just sends back the HTML of my index.html page – Andy Wong May 31 '17 at 15:57
  • May be your app routes `/counselling/triageadmin/getTable` in different routes. It sometimes happen because of order and use of `app.use`. You might wanna consider that. – Tolsee May 31 '17 at 16:02
  • I updated my script to reflect what I did, but it gives me a 404. – Andy Wong May 31 '17 at 17:47

3 Answers3

0

If you move your get on top of your put it should work. The problem seems to be that the static clause resolves your request before it gets to your endpoint, so if you do this:

app.get('/counselling/triageadmin/getTable', function (req, res, next){
    var request = new sql.Request(db);
    request.query('select * from Counselling order by TicketID desc', (err, result) =>{
        if (err) { return next(err); }
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify(result["recordset"]));
    });
});
app.use('/counselling/triageadmin/', express.static(path.join(__dirname, '/build')));

the path to the get will attempt to be matched before you're routed to your static files.

Ideally you would want to have your rest endpoints under a different namespace, i.e. /api but if you decide to keep your setup, this should help.

ruedamanuel
  • 1,930
  • 1
  • 22
  • 23
  • I tried giving each rest endpoint their own name (/getTable by itself), but it would result in a 404. It's only when I have the prefix that I can get a 500 error. – Andy Wong May 31 '17 at 17:18
  • when you did that did you update the path in the front end? It seems to me like you may have forgotten to do that and that would justify the 404 – ruedamanuel May 31 '17 at 17:39
  • Yes I just did it right now; I changed the '/getTable' path in my server.js script, and changed it to axios.get("/getTable"). Still results in 404. – Andy Wong May 31 '17 at 17:45
  • Then you may need to add the full path to your UI call because the relative link may no longer be correct. Try hitting it straight from your browser. – ruedamanuel May 31 '17 at 18:31
0

I think your routes might be conflicting with each other. From the express documentation at: http://expressjs.com/en/4x/api.html#app.use

// this middleware will not allow the request to go beyond it
app.use(function(req, res, next) {
  res.send('Hello World');
});

// requests will never reach this route
app.get('/', function (req, res) {
  res.send('Welcome');
});

Thus, your route '/counselling/triageadmin/getTable' will never be reached, because your route '/counselling/triageadmin/' is intercepting it, responding with static resources.

To solve this, try organizing your routes in a way that puts all of your API requests at a different subfolder, like '/api'. So your getTable endpoint would be located at: '/api/counselling/triageadmin/getTable/' or something like that.

Jurassic_C
  • 2,373
  • 3
  • 22
  • 19
  • Hey, I actually tried setting each route to it's own. As I said in a comment below, I set it as '/getTable' path in my server.js script, and changed it to axios.get("/getTable"). It results in a 404. – Andy Wong May 31 '17 at 17:46
  • Have you attempted to request the URL using an external tool such as Curl or Postman? – Jurassic_C May 31 '17 at 19:41
0

I'm also learning the MEAN stack and I stumbled upon your question since I had the opposite problem. I wanted it to respond with an HTML instead of a JSON

this line of code MAKES it respond with an HTML

res.send(JSON.stringify(result["recordset"]));

(I tried res.send("<h3 HTML T_T </h3>");) and it did send and HTML

however, if you try

res.json(String(req.params.id)); <= Notice the res.json instead of res.send

It responds with a JSON :) I hope this helped

Skrmnghrd
  • 558
  • 4
  • 10