React app Express Api无法运行localhost 404(未找到)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React app Express Api无法运行localhost 404(未找到)相关的知识,希望对你有一定的参考价值。

当我单击提交按钮时,此应用程序应在api中添加信息当我单击添加任务的页面上的按钮时,我不断收到“ POSThttp://localhost:3000/api/task404(未找到)”,我尝试了所有我知道的东西,并在互联网上找到了,但是我没有解决问题,所以我请您帮忙使我的React应用正常运行,我得到这个“ SyntaxError:意外的令牌

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;
答案

不要像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'
                }
            })

以上是关于React app Express Api无法运行localhost 404(未找到)的主要内容,如果未能解决你的问题,请参考以下文章

跨域会话 Cookie(Heroku 上的 Express API + Netlify 上的 React App)

在 Netlify 上部署时使用 Express 公开 API 路由

express 无法从 url 获取查询参数 [重复]

使用express, create-react-app, mongodb搭建react模拟数据开发环境

React App 和 node.js 后端 api 安全获取

create react app遇到的问题