reactjs - 无法从我的 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, …}
解决方案
尝试
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
推荐阅读
- ffmpeg - 使用带有叠加网络摄像头的 ffmpeg 的 kmsgrab 设备记录 Linux Wayland/DRM 屏幕
- html - 不应该在移动菜单上显示的链接,在活动和悬停时
- angular - 如何在单个 index.html 文件中编译角度构建,该文件将从 http get 请求提供
- rust - 函数类型定义可以单独一行而不是内联吗?
- android - 将数据插入sqlite数据库时如何避免重复值?
- c# - 从 Azure 计算机视觉 API 提取文本时出错
- reactjs - 反应排除路线
- java - I want visible button has removed it text from TextView
- django - 来自芹菜任务延迟的Keyerror
- php - 使用 Google Optimize A/B 测试进行服务器端重定向