首页 > 解决方案 > 无法从我的 Express 服务器向 React 前端发送响应字符串

问题描述

我想用字符串格式的 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, …}

标签: reactjsexpressresponsehttpresponse

解决方案


尝试

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


推荐阅读