304 Status on Page Refresh

家住魔仙堡 提交于 2021-02-05 11:20:47

问题


I’m making a music playlist/blog website using React, Node/Express, and PostgreSQL. I'm deploying using Heroku. Here is a link to the live app:

Live app: https://earth-nights.herokuapp.com/

When the user clicks on the “Earth Nights #1” card on the homepage, the user is taken to the content page for that particular playlist (https://earth-nights.herokuapp.com/episode/1). That’s great, but when I refresh the page, I only see the API info for that page:

{
"id": 1,
"title": "Earth Nights #1",
"date_of_show": "April 24, 2020",
"teaser": "Welcome to the first Earth Nights playlist!",
"card_image": "https://cdn.technologynetworks.com/tn/images/thumbs/jpeg/640_360/the-psychedelic-revolution-in-psychiatry-333007.jpg"
}

I have followed the instructions on this page to disable all caching for Node.js apps: https://devcenter.heroku.com/articles/nodejs-support#cache-behavior, and the problem is still happening.

Is there something I am doing wrong with caching, or any other issues that you can see? My server code is below. I would greatly appreciate any insight that you could provide.

index.js

const express = require('express');
const app = express();
const cors = require('cors');
const pool = require('./db');
const path = require("path");

const PORT = process.env.PORT || 5000;

//middleware
app.use(cors());
app.use(express.json());


app.use(express.static("client/build", {
  etag: true, // Just being explicit about the default.
  lastModified: true,  // Just being explicit about the default.
  setHeaders: (res, path) => {
    const hashRegExp = new RegExp('\\.[0-9a-f]{8}\\.');

    if (path.endsWith('.html')) {
      // All of the project's HTML files end in .html
      res.setHeader('Cache-Control', 'no-cache');
    } else if (hashRegExp.test(path)) {
      // If the RegExp matched, then we have a versioned URL.
      res.setHeader('Cache-Control', 'max-age=31536000');
    }
  },
}));

if(process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "client/build")));
}

console.log(__dirname);
console.log(path.join(__dirname, "client/build"));

//routes

//get all episodes
app.get('/episode', async (req, res) => {
  try {
    const allEpisodes = await pool.query("SELECT * FROM card ORDER BY id DESC");
    res.json(allEpisodes.rows);
  } catch (err) {
    console.error(err.message);
  }
});


//select one episode
app.get('/episode/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const episodeContent = await pool.query(
      "SELECT * FROM card WHERE id = $1", [
      id
    ]);

    res.json(episodeContent.rows[0])
  } catch (err) {
    console.error(err.message)
  }
});

app.get('/episode/:id/playlist', async (req, res) => {
  try {
    const { id } = req.params;
    const episodeContent = await pool.query(
      "SELECT * FROM playlist WHERE episode = $1", [
      id
    ]);

    res.json(episodeContent.rows)
  } catch (err) {
    console.error(err.message)
  }
});

app.post("/send", async (req, res) => {
  try {
    const { name, email, message } = req.body;
    const newMessage = await pool.query(
      "INSERT INTO messages (name, email, message) VALUES ($1, $2, $3) RETURNING *", [
        name,
        email,
        message
      ]
    );
    res.json(newMessage.rows[0]);
  } catch (err) {
    console.error(err.message)
  }
});


app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname, "client/build/index.html"));
});

app.listen(PORT, () => {
  console.log(`server has started on http://localhost:${PORT}`);
});

回答1:


My problem is solved! I didn't realize that it was a problem to use the same routes for my server and client sides, and that was what was causing the page reload to display the JSON data instead of the actual content of the page. So I just changed my server-side routes to include '/api' before the actual name of the route, and that fixed the problem.



来源:https://stackoverflow.com/questions/61515999/304-status-on-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!