Wednesday, 28 October 2020

GET request returns index.html doc instead of json data

After deploying my mern app to heroku, the GET request to the root route ('http://localhost:8000/') is now returning index.html doc instead of json data from the request. I'm getting 200 status code but the response is html. This is happening locally and in production.
The request was working before I deployed the app to Heroku and connected index.html (client app) to the server. All the other requests are working except this one.

I've been trying to fix this for a few days now.

How can I solve this? Thanks!

route/controller - list posts

router.get('/', (list)) 

exports.list = (req, res) => {
  const sort = { title: 1 };
  Post.find()
    .sort(sort)
    .then((posts) => res.json(posts))
    .catch((err) => res.status(400).json("Error: " + err));
};

server.js

// imports 

const authRoutes = require("./routes/auth");
const userRoutes = require("./routes/user");
const postRoutes = require("./routes/posts");
// app
const app = express();

const url = process.env.MONGODB_URI 
mongoose.connect(url, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
});
mongoose.connection
  .once("open", function () {
    console.log("DB Connected!");
  })
  .on("error", function (error) {
    console.log("Error is: ", error);
  });

// middlewares
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Credentials", true);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
  next();
});

app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(expressValidator());
app.use(cors());
 
 app.use(express.static(path.join(__dirname, './client/build')))

if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
}
app.get("/*", function (req, res) {
  res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
app.use(authRoutes);
app.use(userRoutes);
app.use(postRoutes);

const port = process.env.PORT || 80;

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

ListPosts.js

class ListPosts extends React.Component {
    state = {
        title: '',
        body: '',
        date: '',
        posts: []
    }

    componentDidMount = () => {
        this.getPosts()
    }

   getPosts = () => {
        axios.get(`${API}`)
        .then((response) => {
            const data = response.data
            this.setState({posts: [data]})
            console.log(data)
        })
        .catch((error) => {
            console.log(error)
        })
    }
     
    displayPosts = (posts) => {
        if (!posts.length) return null;
      posts.map((post, index) => (
            <div key={index}>
            <h3 className="posts-title">{post.title}</h3>
           ...
            </div>    
        ))
    }


    render() {
        return (
         <div>
           {this.displayPosts(this.state.posts)}
           </div>
        )
    }
}

export default ListPosts

package.json

 "scripts": {
    "start": "node server.js",
    "start:dev": "nodemon server.js",
    "heroku-postbuild": "cd client && npm install && npm run build"
  },


from GET request returns index.html doc instead of json data

No comments:

Post a Comment