【发布时间】:2021-01-06 20:21:24
【问题描述】:
我正在尝试使用 NodeJs 在 MYSql 表中插入数据,Express 框架使用 POST 方法抛出 Postman。我得到一个错误。我不知道这是否与json的解析有关。或者我必须发送不同的。
从邮递员发送的Json(原始,JSON):
{
"namel": "Teusaquillo",
"area_2m": 6000,
"parent": "chapinero"
}
当我发送请求时,我收到此错误:
<pre>SyntaxError: Unexpected token in JSON at position 3<br> at JSON.parse (<anonymous>)<br> at parse (<mypaht>\nodeapi\node_modules\body-parser\lib\types\json.js:89:19)<br> at <mypaht>\node_modules\body-parser\lib\read.js:121:18<br> at invokeCallback (<mypaht>nodeapi\node_modules\raw-body\index.js:224:16)<br> at done (<mypaht>\node_modules\raw-body\index.js:213:7)<br> at IncomingMessage.onEnd (<mypaht>\node_modules\raw-body\index.js:273:7)<br> at IncomingMessage.emit (events.js:326:22)<br> at endReadableNT (_stream_readable.js:1252:12)<br>  `; at processTicksAndRejections (internal/process/task_queues.js:80:21)</pre>
错误的其他观点:
SyntaxError: Unexpected token in JSON at position 3
at JSON.parse (<anonymous>)
at parse (<mypaht>\node_modules\body-parser\lib\types\json.js:89:19)
at <mypaht>\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (<mypaht>\node_modules\raw-body\index.js:224:16)
at done (<mypaht>\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (<mypaht>\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (events.js:326:22)
at endReadableNT (_stream_readable.js:1252:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
这是 index.js 文件:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const mysql = require('mysql');
app.use(bodyParser.json());
//create database connection
const conn = mysql.createConnection({
...
});
//connect to database
conn.connect((err) =>{
...
});
app.post('/api/locations',(req, res) => {
let data = {namel: req.body.namel, area_2m: req.body.area_2m, parent: req.body.parent};
let sql = "INSERT INTO location SET ?";
let query = conn.query(sql, data,(err, results) => {
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
这是我要填写的表格:
CREATE TABLE `location` (
`namel` char(100) NOT NULL,
`area_2m` int(11) DEFAULT NULL,
`parent` char(100) DEFAULT NULL,
PRIMARY KEY (`namel`),
KEY `parent` (`parent`),
CONSTRAINT `location_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `location` (`namel`)
)
感谢您的帮助。谢谢!
【问题讨论】:
-
您是否尝试在其他工具中发送请求?比如失眠。只是为了排除工具的影响。
-
你的问题解决了吗?
-
在失眠中我得到这个错误。 SyntaxError:JSON.parse (
) 位置 2 处的 JSON 中的意外标记 -
@JRichardsz 还没有。我进行了调试,错误出现在 ge 进入函数之前
-
你能试试这个
curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:3000/data吗??
标签: node.js json express post postman