0

I'm new react and nodejs and full stack development in general. I'm trying to make a login page in nodejs/react/mysql. Right now, I'm just trying to do get request for the main login page. I think I'm struggling with connecting the front and backend and the moment.

Nodejs app.js:

const express = require('express');
const bodyparser = require('body-parser');
const cors = require('cors');
const app = express();
const mysql = require('mysql');



let connection = mysql.createConnection({
 //Connection is encrypted for security reasons. 
 host: '***********',
 user: '***********t',
 password: '***********',
 database: '***********'
});

 connection.connect(function(err) {
 if (err) {
 return console.error('error: ' + err.message);
 }

 console.log('Connected to the MySQL server.');
});



app.listen(3001, () => { console.log('running on port 3001'); });

app.use(cors()); 
app.use(express.json()); a
app.use(bodyparser.urlencoded({extended: true}));

 app.get('/', (req, res) => { res.send('respond with a resource'); });

componentDidMount() react code/fetch request:

  componentDidMount() {
  // GET request using fetch with error handling
  fetch('/')
     .then(async response => {
         const data = await response.text();
        // console.log(data);
            console.log('test',data);

        // check for error response
        if (!response.ok) {
            // get error message from body or default to response statusText
            const error = (data && data.message) || response.statusText;
            return Promise.reject(error);
        }

        this.setState({ totalReactPackages: data.total })
    })
    .catch(error => {
        this.setState({ errorMessage: error.toString() });
        console.error('There was an error!', error);
    });
   } 

My sql connection works fine, I think it's an issues connecting the front end and backend. Changing following line:.

    const data = await response.text();

to:

    const data = await response.json();

Returns the following error:

  There was an error! SyntaxError: Unexpected token < in JSON at position 0

This is the html it returns in the following screenshot:

enter image description here

Once I figure out how to connect the front end and backend the rest of the project should be easyish to do. The react UI work and my SQl connection works fine. Any help would be greatly appreciated.

4
  • are you doing server rendering? if not then fetch url needs to be something like localhost:3001 to connect to your express server Commented Nov 23, 2020 at 3:44
  • I don't see the difference between what the line of code was, and what it was changed to. You should probably also check repsonse.ok before trying to unpack the response text/json. Why are you mixing async/await and promise chaining? Commented Nov 23, 2020 at 3:47
  • Sorry typo. Should be fixed now Commented Nov 23, 2020 at 3:49
  • Does Proxying API Requests in Development help you? Commented Nov 23, 2020 at 6:29

2 Answers 2

2

You're currently fetching data from the primary site, not the Node.js site you've created.

You should change the fetch to:

fetch('http://localhost:3001')

Additional information

The response you are sending from the backend isn't JSON:

res.send('respond with a resource');

To send JSON, you should use:

res.json({ message: "respond with a resource" });

Then you'll be able to use:

const data = await response.json();

And access the data via:

const message = data.message;
Sign up to request clarification or add additional context in comments.

6 Comments

I seem to be getting the same error: There was an error! SyntaxError: Unexpected token < in JSON at position 0
If you use const data = await response.text(); console.log(data); what's the output?
Just more of that html.
Ok, that's the reason you're getting the error. HTML can't be parsed as JSON. You'll need to figure out where the HTML is coming from. Did you post the actual node.js code or is that just an example?
I have a bunch of code thats commented out, but that should be all the nodejs code i believe.
|
0

For me it worked just by appending "Https://" to the beginning of the API url.

        fetch(`https://api.openweathermap.org/data/2.5/weather?q=${CITY_NAME}&appid=${API_KEY}`)

It took me days and 10s of articles/SO threads to figure out that when doing dev on your local machine the fetch request gets routed to local html document.

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.