我正在POST
将数据发送到我的express
(v.4+) 服务器。但是,我在浏览器中得到的响应采用以下形式:
响应 {type: "cors", url: "http://localhost:1111/", status: 200, ok: true, …}
具体来说,响应的body
是一个ReadbleStream
,而不是我期望的json
或string
我发回的回复。
服务器代码是:
mongoose.connect('mongodb://localhost/block');
const app = express();
app.set('port', 1111);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/', (req, res, next) => { // for cors
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Credentials', true);
next();
});
app.post('/', (req, res) => {
const { dataType, table } = req.body;
const { rows } = table;
const log = {
msgArray: []
};
function saveData(dbModel) {
rows.forEach(row => {
row.data_initiated = new Date();
row.status = 'initiated';
const entry = new dbModel(row);
entry.save(err => {
if (err) {
log.msgArray.push({ err });
}
log.msgArray.push({
msg: 'saved!'
});
});
});
}
if (dataType === 'Contract') {
saveData(Contract);
} else if (dataType === 'Commodity') {
saveData(Commodity);
} else {
saveData(Client);
}
res.send(log).end();
我在客户端使用fetch
来POST
数据。
如何才能正确地将 json/string
发送回用户?
谢谢
最佳答案
当使用fetch
时,响应必须转换为JSON
并返回。在接下来的then
中,可以使用转换后的值。
fetch( url, config)
.then( res => res.json())
.then( json => {
console.log( json );
...
}
值得一提的是,这与我们在使用 Axios.js(基于 Promise 的 AJAX 库)时处理响应的方式有点不同。
P.S:我更新了问题以修复代码,以便正确发送响应。
关于javascript - Express服务器响应是一个流,如何使其成为字符串/json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49922484/