簡體   English   中英

創建用於在 React.js 中添加問題的腳本

[英]Create script for adding question in React.js

我正在制作一個腳本來在 react.js 和 mongodb 中添加問答。 按下按鈕時出現問題會產生以下錯誤

加載資源失敗:服務器響應狀態為 404(未找到) create-quest.component.js:40 Object 數據:“↵↵↵↵Error↵↵↵

Cannot POST /create
↵↵↵”狀態:404 statusText:“未找到”標頭:{access-control-allow-origin:“*”,連接:“關閉”,內容長度:“146”,內容安全策略:“默認-src 'none'", 內容類型: "text/html; charset=utf-8", ...} config: {url: " http://localhost:3000/create ", 方法: "post", data: "{"title":"aaa","content":"aaa "}", headers: {…}, transformRequest: Array(1), …} request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …} proto : Z497031794414A552435F9015ZAC1

我的代碼是:

 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> ) } }

我是 node react 和 mongo 的初學者,我不明白錯誤在哪里

這是后端代碼的問題,而不是前端代碼的問題。 Cannot POST /create行是這里的關鍵信息。 查看您定義路由處理程序的位置,如果您使用 Express,請確保您有類似app.post('/create', (req, res) => { /** some code here **/ }

編輯:由於您已經包含了一些代碼,我猜您要么沒有告訴您的 Express 應用程序使用路由器,要么您給了它一個不是根 ( '/' ) 的掛載點,所以它正在尋找將您的請求作為/<mount point>/create而不是/create 確保您的后端應用程序/服務器文件中有一行說明app.use(router)並注意沒有提供安裝路徑,因此它將在/create上查找請求。

但是,在您的路由文件中,您嘗試導出路由 function 以及您的路由器,但是您正在覆蓋module.exports object,而不是同時導出它們。 您可能希望將這些行更改為:

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

module.exports.router = router

這是我的路線代碼

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;

我的 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM