sei-ec-remote / project-4-issues

Open an issue to receive help on project 4
0 stars 0 forks source link

GET http://localhost:8000/api/classes 404 (Not Found) #256

Closed noahD0zer closed 11 months ago

noahD0zer commented 11 months ago

What stack are you using?

(ex: MERN(mongoose + react), DR(django + react), PEN, etc.)

mern

What's the problem you're trying to solve?

api fetch unsucessful

Post any code you think might be relevant (one fenced block per file)

//routes/charactercreate_routes.js
router.get('/classes', async (req, res) => {
  try {
    const classes = await Class.find({}, 'class');
    const classData = classes.map((classObj) => ({ class: classObj.class }));
    res.json(classData);
  } catch (err) {
    console.error('Error fetching classes:', err);
    res.status(500).json({ error: 'Internal server error' });
  }
});

//models/class.js
const mongoose = require('mongoose');

const classSchema = new mongoose.Schema({
  class: String,
  proficiencyName: String,
});

module.exports = mongoose.model('Class', classSchema);

//src/CreateCharacter.jsx
  useEffect(() => {
    // Fetch class data from backend API
    fetch('http://localhost:8000/api/classes')
      .then((response) => response.json())
      .then((data) => {
        // Extract only the class names
        const classNames = data.map((classObj) => classObj.class);
        // Set the class names in component state
        setClasses(classNames);
      })
      .catch((error) => console.error('Error fetching classes:', error));
  }, []);

  useEffect(() => {
    // Fetch race data from backend API
    fetch('http://localhost:8000/api/races')
      .then((response) => response.json())
      .then((data) => {
        // Extract only the race names
        const raceNames = data.map((raceObj) => raceObj.race);
        // Set the race names in component state
        setRaces(raceNames);
      })
      .catch((error) => console.error('Error fetching races:', error));
  }, []);

  const generateButtonRows = (options, field) => {
    const rows = [];
    for (let i = 0; i < Math.ceil(options.length / 4); i++) {
      const row = (
        <div key={i} style={{ display: 'flex' }}>
          {options.slice(i * 4, (i + 1) * 4).map((option) => (
            <button
              key={option}
              onClick={() => handleButtonClick(option, field)}
              style={{ margin: '4px' }}
            >
              {option}
            </button>
          ))}
        </div>
      );
      rows.push(row);
    }
    return rows;
  };

  return (
    <div>
      <h1>Create Character</h1>
      <form onSubmit={handleSubmit}>
        <div>
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              cursor: 'pointer',
            }}
            onClick={() => toggleExpansion('background')}
          >
            <span style={{ marginRight: '8px' }}>Background</span>
            {isBackgroundExpanded ? '▲' : '▼'}
          </div>
          {isBackgroundExpanded && <div>{generateButtonRows(backgrounds, 'background')}</div>}
        </div>

        <div>
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              cursor: 'pointer',
            }}
            onClick={() => toggleExpansion('race')}
          >
            <span style={{ marginRight: '8px' }}>Race</span>
            {isRaceExpanded ? '▲' : '▼'}
          </div>
          {isRaceExpanded && <div>{generateButtonRows(races, 'race')}</div>}
        </div>

        <div>
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              cursor: 'pointer',
            }}
            onClick={() => toggleExpansion('characterClass')}
          >
            <span style={{ marginRight: '8px' }}>Class</span>
            {isClassExpanded ? '▲' : '▼'}
          </div>
          {isClassExpanded && <div>{generateButtonRows(classes, 'characterClass')}</div>}
        </div>

        {/* Other fields for abilities, proficiencies, etc. */}
        <button type="submit">Create Character</button>
      </form>
    </div>
  );
}

export default CreateCharacter;

If you see an error message, post it here. If you don't, what unexpected behavior are you seeing?

CreateCharacter.jsx:82 GET http://localhost:8000/api/classes 404 (Not Found)

What is your best guess as to the source of the problem?

incorrect usage of fetch call?

What things have you already tried to solve the problem?

I have tried refactoring models and routes, making sure they are exported and refactoring fron end.

Paste a link to your repository here https://github.com/noahD0zer/BG3-Creator-Frontend

timmshinbone commented 11 months ago

Share your backend route you're trying to hit, and the small section where they're registered in server.js

noahD0zer commented 11 months ago

//required route is routes/charactercreate_routes.js

// require route files const userRoutes = require('./app/routes/user_routes') const characterCreateRoutes = require('./app/routes/charactercreate_routes')

// register route files app.use(userRoutes) app.use(characterCreateRoutes)

timmshinbone commented 11 months ago

Alrighty, it's 1:1 time!