【问题标题】:Trouble sending a response string from my Express server to React front-end [duplicate]无法从我的 Express 服务器向 React 前端发送响应字符串 [重复]
【发布时间】:2019-08-14 23:34:42
【问题描述】:

我想用字符串格式的 URL 回复 Fetch 请求。我见过的例子看起来很简单,但我相信我的 cors 中间件可能会搞砸一些事情。

这是我的服务器:

const express = require('express');
const cors = require('cors');
const db = require('./database/db');
const app = express();

app.use(cors());
app.use(require('./router.img.js'));
app.listen(4000, console.log('Listening on 4000'));

module.exports = app;

这里是我发送响应的地方:

exports.postImage = (req, res) => {
  let sliceIndex = req.file.originalname.indexOf('.');
  let fileType = req.file.originalname.slice(sliceIndex);
  let url = "https://instaimages.sfo2.digitaloceanspaces.com/" + 
  req.body.number + fileType;

  res.set('Content-Type', 'text/html'); 
  res.send(url);
};

我在前端看到一个响应,但它不包含 URL 字符串。这是它的样子:

Response {type: "cors", url: "http://localhost:4000/upload/", 
redirected: false, status: 200, ok: true, …}

【问题讨论】:

  • 为什么res.set('Content-Type', 'text/html') .. 你发送的不是 html 的 url?
  • 我正在尝试仅发送字符串,这是在类似问题上推荐的。当我删除它时,我在前端有相同的响应
  • 你试过text/plain吗?
  • 刚试了一下,同样的反应。我应该注意到 res.body 以 ReadableStream {locked: false} 的形式返回

标签: reactjs express response httpresponse


【解决方案1】:

试试

fetch('/your/api/endpoint')
  .then(res => res.text())
  .then(text => console.log(text));

fetch 实际上解析为Response 对象,您需要从该对象中执行额外的步骤来提取所需的数据。更多信息在这里:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

【讨论】:

  • 是的,非常感谢。看起来我需要阅读更多 Fetch 的文档,我可以发誓这是我的服务器的问题。
猜你喜欢
  • 2020-11-06
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
  • 2018-11-02
相关资源
最近更新 更多