Реагирует приложение Express Api, не работает localhost 404 (не найдено) - PullRequest
0 голосов
/ 30 сентября 2019

это приложение должно добавить информацию в API, когда я нажимаю кнопку Отправить, я продолжаю получать " POST http://localhost:3000/api/task 404 (не найдено) ", когда я нажимаю кнопку на странице, котораядобавив задачу, я перепробовал все то, что знаю, и нашел в интернете, но не решил проблему, поэтому прошу вашей помощи, чтобы мое приложение прореагировало так же, как я получаю " SyntaxError: Неожиданный токен <в JSONв позиции 0</strong>"

Файл Server.js

const express = require('express');
const morgan = require('morgan');
const path = require('path');
const  { mongoose } = require('./database');
const app = express();
// Import the library:
var cors = require('cors');


// Then use it before your routes are set up:
app.use(cors());

//Settings
app.set('port', process.env.PORT || 3000);

//Middlewares
app.use(morgan('dev'));
app.use(express.json());



//Routes

app.use('/api/task' ,require('./routes/task.routes'));


//static files


app.use(express.static(path.join(__dirname,'public')));


//Start server
app.listen(app.get('port'), ()=>{
    console.log(`Server on port ${app.get('port')}`);
});

Файл Data.js

import React, {Component} from 'react';
import M from 'materialize-css';
class Data extends Component {


    constructor(){
        super();
        this.state = {
            title :'',
            img : '',
            price:0,
            more:'',
            task:[],
            _id:''
        };
        this.handleChange = this.handleChange.bind(this);
        this.addTask = this.addTask.bind(this);
    }

    addTask(e){
        if(this.state._id){
            fetch(`http://localhost:3000/api/task/${this.state._id}`,{
                method: 'PUT',
                body: JSON.stringify(this.state),
                headers: {
                    'Accept' : 'application/json',
                    'Content-Type': 'application/json'
                }

            })
            .then(res => res.json())
            .then(data =>{ 
                console.log(data)
                M.toast({html: 'Task Updated'});
                this.setState({title: ' ',img: '', price:0,more:'', _id: ''});
                this.fetchTask();

            });
        }else{
            fetch('http://localhost:3000/api/task',{
                method: 'POST',
                body: JSON.stringify(this.state),
                headers: {
                    'Accept' : 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            .then(res => res.json())
            .then(data => {
                console.log(data)
                M.toast({html: 'Task Saved'});
                this.setState({title:'', img: '' , price:0 ,more:''});
                this.fetchTask();
            })
            .catch(err => console.error(err));
        }

        e.preventDefault();
    }

    componentDidMount(){
        this.fetchTask();
    }

    fetchTask(){
        fetch('http://localhost:3000/api/task')
            .then(res => res.json())
            .then(data => {
                this.setState({task: data});
                console.log(this.state.task);
            });
    }

    deleteTask(id){
            // eslint-disable-next-line no-restricted-globals
            if(confirm('Are you sure you want to delete it?')){

                fetch(`http://localhost:3000/api/task/${id}`,{
                    method: 'DELETE',
                    headers: {
                        'Accept' : 'application/json',
                        'Content-Type': 'application/json'
                    }
                })
                .then(res => res.json())
                .then(data => {
                    console.log(data);
                    M.toast({html: 'Task Deleted'});
                    this.fetchTask();
                });
              }
            }

    editTask(id){
        fetch(`http://localhost:3000/api/task/${id}`)
        .then(res => res.json())
        .then(data => {
            console.log(data)
            this.setState({
                title: data.title,
                img: data.img,
                price: data.price,
                more: data.more,
                _id: data._id
            })
        });
    }

    handleChange(e){
        const {name, value} = e.target;
        this.setState({
            [name]: value
        });
    }





    render(){
        return(
        <div>
            {/* navigacion*/}


            <div className="container">
                <div className="row">
                    <div className="col s10">
                             <div className="col s10">
                             <div className="card">
                                <div className="card-content">
                                    <form onSubmit={this.addTask}>
                                        <div className="row">
                                            <div className="input-field col s7">
                                                <input name="title" value={this.state.title} onChange={this.handleChange} type="text" placeholder="Insert Title"/>
                                            </div>   
                                        </div>
                                        <div className="row">
                                            <div className="input-field col s7">
                                                <textarea name="img" value={this.state.description} required={true} onChange={this.handleChange} placeholder="Insert img" 
                                                className="materialize-textarea"></textarea>
                                            </div>  
                                        </div>
                                        <div className="row">
                                            <div className="input-field col s7">
                                                <input name="price" value={this.state.price} required={true} onChange={this.handleChange} type="Number" placeholder="Insert Price"/>
                                            </div>   
                                        </div>
                                        <div className="row">
                                            <div className="input-field col s7">
                                                <input name="more" value={this.state.more} required={true} onChange={this.handleChange} type="text" placeholder="Insert more"/>
                                            </div>   
                                        </div>
                                            <button type="submit" className="btn light-blue 
                                            darken-4">
                                                Send
                                            </button>
                                    </form>
                                </div>
                             </div>
                    </div>
                    </div>
                    <div className="col-s7">
                        <table >
                                <thead> 
                                    <tr> 
                                        <th>Title</th>
                                        <th>Img</th>
                                        <th>Price</th>
                                        <th>Info</th>   
                                    </tr> 
                                </thead> 
                                <tbody >
                                    {
                                        this.state.task.map(task => {
                                            return(
                                                <tr key={task.id}>
                                                        <td>{task.title}</td>
                                                        <td>{task.img}</td>
                                                        <td>{task.price}</td>
                                                        <td>{task.info}</td>
                                                        <td>
                                                        <button className="btn light-blue darken-4"onClick={()=> this.deleteTask(task._id)} >
                                                        <i className="material-icons">delete</i>
                                                        </button>
                                                        <button onClick={()=> this.editTask(task._id)} className="btn light-blue darken-4" style={{margin:'4px'}}>
                                                        <i className="material-icons">edit</i>
                                                        </button>
                                                        </td>
                                                </tr>
                                            )
                                        })
                                    } 
                                </tbody> 
                        </table>   
                    </div> 
                </div>
            </div>
        </div>
        )

    }
}

export default Data;

Файл маршрутов задачи

    const express = require('express');
const router = express.Router();
const Task = require('../models/task');

router.get('/',async(req,res)=>{
    const tasks = await Task.find();
    console.log(tasks);
    res.json(tasks);
} );


router.get('http://localhost:3000/api/task/:id',async(req,res)=>{
    const tasks = await Task.findById(req.params.id);
    console.log(tasks);
    res.json(tasks);
} );

router.post('http://localhost:3000/api/task', async(req,res)=>{
    const { title,img, price, info } = req.body;
    const task = new Task({
        title:title,
        img:img,
        price:price,
        info:info

    });
    await task.save();
    res.json({status :'Task saved'});
});


router.put('http://localhost:3000/api/task/:id',async (req,res)=>{
    const  { title,img, price,info } = req.body;
    const newTask = {
        title:title,
        img:img,
        price:price,
        info:info

    };
    await Task.findByIdAndUpdate(req.params.id,newTask);
    res.json({status : 'Task Updated'});
});

router.delete('http://localhost:3000/api/task/:id', async(req,res)=>{
    await Task.findByIdAndRemove(req.params.id);
    res.json({status:'Task Deleted'});
});


module.exports = router;

1 Ответ

0 голосов
/ 30 сентября 2019

Не преобразовывать Объект в string как body: JSON.stringify(this.state).

Просто передайте это как тип объекта JSON.

 fetch('http://localhost:3000/api/task',{
                method: 'POST',
                body: this.state,
                headers: {
                    'Accept' : 'application/json',
                    'Content-Type': 'application/json'
                }
            })
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...