如何在API中发送响应

我有一个具有以下路由的api:

const express = require('express');
const api = express.Router();

const exampleCtrl = 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
ramzismo 回答:如何在API中发送响应

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2912298.html

大家都在问