javascript - 关于连接 React 和 NodeJS express 的问题
问题描述
我试图在 React(Front End) 和 NodeJs(BackEnd) 和 NodeJS -> React(GET) 之间连接,但 React -> NodeJS(POST) 总是出错“POST http://localhost:3001/board/giveresult 500 ( Internal Server Error)”和“Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0” 我一直在解决这个问题,但我被困了一周。问题是什么?
// Method in React
setData() {
let data = {
id:this.state.contents.id, //contents is array in the state
write:this.state.contents.writer,
title:this.state.contents.title,
description:this.state.contents.description
}
fetch('http://localhost:3001/board/giveresult'
,{
method: 'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify(data)
})
.then (res => res.json())
.then (data => console.log(data));
}
//NodeJS Express
const express = require('express');
const app = express();
const receive = require('./routes/receive')
const giveResult = require('./routes/giveResult')
const port = process.env.PORT || 3001;
const cors = require('cors');
var bodyParser = require('body-parser');
app.use(cors());
app.use(bodyParser.json())
app.use('/board/giveresult', giveResult);
app.use('/board/receive', receive);
app.listen(port, function(){
console.log(`connected ${port} port!`);
});
//giveResult
var express = require('express');
const router = express.Router();
var mysql = require('mysql');
const dbconfig = require('../mysql.js');
const { Router } = require('express');
const connection = mysql.createConnection(dbconfig);
var bodyParser = require('body-parser');
router.post('/', function(req, res) {
if(err) throw err;
var post = req.body.id;
console.log(post)
res.send('suceess!!!!');
});
module.exports = router;
解决方案
尝试在您的请求标头中添加接受,例如 .
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
推荐阅读
- python - Tensorflow自动输入无形状?
- python - Streamlit 选择框正在重置网页
- python - Pyspark cogroup rdd
- sapui5 - sap.m.table 多复选框使其只读 - 条件 + SAP UI5
- elasticsearch - 是否可以将查询结果用于 ElasticSearch 中的另一个查询?
- c++ - 如何暂停执行,直到用户登录 Win32 上的启动应用程序
- c++ - Cpp 复制到剪贴板事件
- python - Python tkinter:如果我点击 gui,应用程序没有响应
- kubernetes - Kubernetes:应用部署后未创建 Pod
- javascript - 将 getElementById 值传递给文本框值的问题