user7892649
user7892649

Reputation:

Express.js - can find my route

I'm using react.js and express.js and getting 404 error on my fetch request.

I'm simply trying to have my routes return testing express.js...

[app.js]

'use strict';

const NODE_ENV = process.env.NODE_ENV;
const PORT = process.env.PORT;

const next = require('next');
const express = require('express');
const api = require('./api');

const client = next({ dev: NODE_ENV === 'development' });
const clientHandler = client.getRequestHandler();
const app = express();

client.prepare().then(() => {
  app.use('/api', api);
  app.get('*', (req, res) => clientHandler(req, res));
});

const listener = app.listen(PORT, err => {
  if (err) throw err;
  console.log('listening on port: %d', listener.address().port); //eslint-disable-line
});

[/api/index.js]

'use strict';

const express = require('express');
const app = express();

app.get('/api/test', function (req, res) {
    res.send('testing express.js...');
});

module.exports = app;

[Body.js]

import React from 'react';

export default class Body extends React.Component {
  constructor(props) {
    super(props);    
    this.fetchContacts = this.fetchContacts.bind(this);
  }

  componentDidMount() {
    this.fetchContacts();
  }

  async fetchContacts() {
        const res = await fetch('/api/test');
    const contacts = await res.json();
    log(contacts);
    this.setState({ contacts });
  }

  render() {
    return <div>hello world!</div>;
  }
}

Question: Why am I getting a 404 error?

Upvotes: 1

Views: 251

Answers (2)

jfriend00
jfriend00

Reputation: 707158

To make your /api/test route work properly, you need to change this:

app.get('/api/test', function (req, res) {
    res.send('testing express.js...');
});

to this:

app.get('/test', function (req, res) {
    res.send('testing express.js...');
});

Your router is already looking at /api so when you then put a route on the router for /api/test, you were actually making a route for /api/api/test. To fix it, make the above change.


Also, your index.js file should not be using an app object. It should be using an express.Router() object, though an app object is also a router so it might kind of work, but it's not the way it should be done.

Upvotes: 1

Cristian David
Cristian David

Reputation: 694

That is not the way to load a react JS file on nodejs, follow this basic (React + NodeJS) guide:

https://blog.yld.io/2015/06/10/getting-started-with-react-and-node-js/#.Wd7zSBiWbyg

Or use "create-react-app" :

https://medium.com/@patriciolpezjuri/using-create-react-app-with-react-router-express-js-8fa658bf892d

Upvotes: 0

Related Questions