VM1411:1 未捕获(承诺中)语法错误:意外的标记“O”,“OK”不是有效的 JSON
当我将
JSON(stringified object)
数据提取到服务器并尝试发送 statusCode
数字 200 以指示其状态为“正常”以便响应时,客户端网页不断收到该错误,原因未知。服务器“可以”从客户端获取 JSON,但目前仅检索不起作用。如何发送状态码而不出现错误?
客户端/js/产品/index.js
var lotion = {
name: "Vaseline",
price: 20,
skinProtection: true,
protectionLevel: 10
};
class Order {
constructor(method, target) {
this.method = method;
this.target = target;
this.serve();
}
options(method, target) {
return {
method: method,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(target)
}
}
readAPI(path) {
return fetch(`http://localhost:3500/controllers/product/${path}`, this.options(this.method, this.target))
}
async serve() {
let receive = await (await this.readAPI('order')).json();
console.log(receive);
}
}
let getOrder = new Order('post', lotion)
服务器/应用程序/控制器/index.js
const express = require('express');
const controllers = express.Router();
controllers.post('/product/order', async (req, res) => {
console.log(req.body);
res.sendStatus(200); // This causes that the browser receives an error
})
module.exports = controllers; // all the name must be matched
服务器/应用程序/app.js
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
const app = express();
app.use(cors());
app.use(express.json());
const controllers = require('./controllers/index.js');
app.use('/controllers', controllers)
module.exports = app;
服务器/index.js
const app = require('./app/app.js');
app.listen(process.env.PORT, () => {
console.log(`port: ${process.env.PORT}`);
})
文件结构图
.
├── client/
│ ├── js/
│ │ ├── index/
│ │ └── product/
│ │ └── index.js
│ └── pages/
│ ├── index.html
│ └── product.html
└── server/
├── app/
│ ├── controllers/
│ │ └── index.js
│ └── app.js
├── .env
├── node_modules
├── index.js
├── package-lock.json
└── package.json
尝试
.json({message: "OK"})
上添加了 res.sendStatus(200)
。在您的
index.js
文件中,您有以下代码:
async serve() {
let receive = await (await this.readAPI('order')).json();
console.log(receive);
}
这会在您从服务器接收到的响应上调用
.json()
,但此响应已经是 JSON 格式。
您想将此代码更改为如下所示:
async serve() {
const receive = await this.readAPI('order');
const value = JSON.parse(receive);
console.log(value);
}
您现在应该在控制台中看到正确的值。