React app Express API 不起作用 localhost 404(未找到)



当我点击按钮提交时,这个应用程序应该在 API 中添加信息 当我单击页面上添加任务的按钮时,我一直收到">POST http://localhost:3000/api/task 404(未找到(",我尝试了所有我知道的事情,我在互联网上找到了,但我没有解决问题,所以我请你帮助让我的反应应用程序工作,因为我得到这个">语法错误:在位置 0 的 JSON 中意外<令牌">

服务器.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')}`);
});

数据.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;

不要像body: JSON.stringify(this.state)那样将对象转换为string

只需将其作为 JSON 对象类型传递即可。

fetch('http://localhost:3000/api/task',{
method: 'POST',
body: this.state,
headers: {
'Accept' : 'application/json',
'Content-Type': 'application/json'
}
})

最新更新