0
votes

I'm making a script to add Q&A in react.js and mongodb. I have a problem when pressing a button creates the following errors

Failed to load resource: the server responded with a status of 404 (Not Found) create-quest.component.js:40 Object data: "↵↵↵↵Error↵↵↵

Cannot POST /create
↵↵↵" status: 404 statusText: "Not Found" headers: {access-control-allow-origin: "*", connection: "close", content-length: "146", content-security-policy: "default-src 'none'", content-type: "text/html; charset=utf-8", …} config: {url: "http://localhost:3000/create", method: "post", data: "{"title":"aaa","content":"aaa"}", headers: {…}, transformRequest: Array(1), …} request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …} proto: Object

my code is:

import React, { Component } from 'react';
import axios from 'axios';

export default class CreateQuest extends Component {

    constructor(props) {
        super(props)

        this.onChangeTitle = this.onChangeTitle.bind(this);
        this.onChangeContent = this.onChangeContent.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {
            title: '',
            content: ''
        }
    }

    onChangeTitle(e) {
        this.setState({ title: e.target.value })
    }

    onChangeContent(e) {
        this.setState({ content: e.target.value })
    }

    onSubmit(e) {
        e.preventDefault()

        const questionObject = {
            title: this.state.title,
            content: this.state.content
        };

        axios.post('http://localhost:3000/create', questionObject)
        .then(response => { 
            console.log(response)
        })
        .catch(error => {
            console.log(error.response)
        });

        this.setState({ title: '', content: '' })
    }


    render() {
        return (
            <div className="wrapper">
                <form onSubmit={this.onSubmit}>
                    <div className="form-group">
                        <label>Add title</label>
                        <input type="text" value={this.state.title} onChange={this.onChangeTitle} className="form-control" />
                    </div>
                    <div className="form-group">
                        <label>Add content</label>
                        <input type="text" value={this.state.content} onChange={this.onChangeContent} className="form-control" />
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Create Question" className="btn btn-success btn-block" />
                    </div>
                </form>
            </div>
        )
    }
}

I am beginner in node react and mongo and I dont understand where is error

3
Can you include your backend code that handles the /create route? - awarrier99
Your issue almost definitely lies in your Express app.js or server.js file (or whatever you chose to call it). Can you update your post to include this file, as well as the snippets you posted as answers (and then remove the "answers" as well so others aren't confused by this page) - awarrier99

3 Answers

0
votes

this is my routes code

module.exports = (app) => {
    const questions = require('../controllers/question.controller.js');
    const answers = require('../controllers/answer.controller.js');
    // Create a new Note
    app.post('/questions', questions.create);
    app.post('/questions/:questionId/answers', answers.create);


    // Retrieve all Notes
    app.get('/questions', questions.findAll);

    // Retrieve a single Note with noteId
    app.get('/questions/:questionId', questions.findOne);
    app.get('/questions/:questionId/answers', questions.findOne); // find answers by question id

    // Update a Note with noteId
    app.put('/questions/:questionId', questions.update);

    // Delete a Note with noteId
    app.delete('/questions/:questionId', questions.delete);
}

let mongoose = require('mongoose'),
    express = require('express'),
    router = express.Router();

let question = require('../models/question.model');

router.route('/create').post((req, res, next) => {
    questions.create(req.body, (error, data) => {
        if (error) {
            return next(error)
        } else {
            console.log(data)
            res.json(data)
        }
    })
});

router.route('/').get((req, res) => {
    questions.find((error, data) => {
        if (error) {
            return next(error)
        } else {
            res.json(data)
        }
    })
})

router.route('/edit/:id').get((req, res) => {
    questions.findById(req.params.id, (error, data) => {
        if (error) {
            return next(error)
        } else {
            res.json(data)
        }
    })
})


router.route('/update/:id').put((req, res, next) => {
    questions.findByIdAndUpdate(req.params.id, {
        $set: req.body
    }, (error, data) => {
        if (error) {
            return next(error);
            console.log(error)
        } else {
            res.json(data)
            console.log('Question updated successfully !')
        }
    })
})

router.route('/delete/:id').delete((req, res, next) => {
    questions.findByIdAndRemove(req.params.id, (error, data) => {
        if (error) {
            return next(error);
        } else {
            res.status(200).json({
                msg: data
            })
        }
    })
})

module.exports = router;
0
votes

my app.js

import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'

import Navbar from './components/Navbar'
import Landing from './components/Landing'
import Login from './components/Login'
import Register from './components/Register'
import Profile from './components/Profile'
import Question from './components/Question'
import Answers from './components/Answer'
import CreateQuest from './components/create-quest.component'



class App extends Component {

  render() {
    return (
      <Router>
        <div className="App">
          <Navbar />
          <Route exact path="/" component={Landing} />
          <div className="container">
            <Route exact path="/register" component={Register} />
            <Route exact path="/login" component={Login} />
            <Route exact path="/profile" component={Profile} />
            <Route exact path="/questions" component={Question} />
            <Route exact path="/create" component={CreateQuest} />
            <Route exact path="/answers" component={Answers} />

          </div>
        </div>
      </Router>
    )
  }
}

export default App
0
votes

This is an issue with your backend code, rather than your frontend code. The line Cannot POST /create is the key information here. Look at where you defined your route handlers and, if you're using Express, make sure you have something like app.post('/create', (req, res) => { /** some code here **/ }

Edit: As you have included some of your code, I'm guessing you either didn't tell your Express to app use the router, or you gave it a mount point that is not the root ('/'), so it's looking for your requests as /<mount point>/create rather than /create. Make sure you have a line in your backend app/server file saying app.use(router) and notice that no mount path was provided, so it will look for requests on /create.

However, in your routes file, you are trying to export both the routes function as well as your router, but you are overwriting the module.exports object, rather than exporting them both. You probably want to change those lines to:

module.exports.routes = (app) => ...

and

module.exports.router = router