我有一个使用以下路线的api:
const express = require('express');
const api = express.Router();
const iccidCtrl = require('../controller/example');
api.post('/update-example/:id', exampleCtrl.updateExample);
返回带有消息的json
function updateExample(req, res) {
const id = req.params.id;
try {
res.status(200).send({message: "Hello"});
} catch (error) {
res.status(500).send({ body: error });
}
}
但是当调用api时,不返回任何信息,也不返回状态。我一直在测试request参数到达api,但响应对客户端而言为空
function onClick() {
let id= document.getElementById("idExample").value;
let baseUrl = `http://localhost:8500/api/update-example`;
let updateUrl = `${baseUrl}/${id}`;
fetch(updateUrl, {
method: "POST",
mode: "no-cors"
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
}
Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}
并且如果您尝试将从客户端收到的响应放入res.json()
,则会出现错误:
SyntaxError: Unexpected end of input
at updatedExample.js:10
您必须使用:res.json()
,当您从fetch
处获得回复时>
fetch()的最简单用法是使用一个参数-指向您要获取的资源-并返回包含响应(响应对象)。
这只是一个HTTP响应,不是实际的JSON。 提取来自响应的JSON正文内容,我们使用json()
方法(已定义在Body mixin上,由Request和响应对象。)fetch