gpt4 book ai didi

javascript - React Express 类型错误 : Cannot read property 'then' of undefined

转载 作者:行者123 更新时间:2023-11-28 14:44:58 25 4
gpt4 key购买 nike

我正在尝试在服务器上渲染我的 React 应用程序,以防用户禁用了 javascript,同时也是为了获得更好的搜索结果。但在导出和使用该函数之间的某个地方,我收到了 TypeError: Cannot read property 'then' of undefined 错误。

这是我的一些代码

// serverRender.js
import ReactDOMServer from 'react-dom/server';
import axios from 'axios';

const serverRender = () => {
axios.get(`${config.serverUrl}/api/content`)
.then(res => {
return ReactDOMServer.renderToString(
<App initialData={res.data.content} />
);
})
.catch(console.error);
}

export default serverRender;

然后我将代码注入(inject)到我的 server.js

// server.js
import express from 'express';
import serverRender from './serverRender';

const server = express();
server.get('/', (req, res) => {
serverRender()
.then(content => {
res.render('index', {
content
});
})
.catch(console.error);
});

我也尝试过

// serverRender.js
axios.get(`${config.serverUrl}/api/content`)
.then(res => {
console.log(
ReactDOMServer.renderToString(
<App initialData={res.data.content} />
)
);
})
.catch(console.error);

我确实在控制台上看到了渲染的内容。请告诉我出了什么问题,谢谢!

附:此处完整错误

TypeError: Cannot read property 'then' of undefined
at /.../server.js:19:5
at Layer.handle [as handle_request] (/.../node_modules/express/lib/router/layer.js:95:5)
at next (/.../node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/.../node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/.../node_modules/express/lib/router/layer.js:95:5)
at /.../node_modules/express/lib/router/index.js:281:22
at Function.process_params (/...t/node_modules/express/lib/router/index.js:335:12)
at next (/.../node_modules/express/lib/router/index.js:275:10)
at sass (/.../node_modules/node-sass-middleware/middleware.js:127:14)
at Layer.handle [as handle_request] (/.../node_modules/express/lib/router/layer.js:95:5)

最佳答案

如果您希望它“thenable”,您需要从 serverRender 函数返回一个 promise 。目前,您没有从该函数返回任何内容。

// serverRender.js
const serverRender = () => {
return axios.get(`${config.serverUrl}/api/content`)
.then(res => {
return ReactDOMServer.renderToString(
<App initialData={res.data.content} />
);
})
.catch(console.error);
}

export default serverRender;

关于javascript - React Express 类型错误 : Cannot read property 'then' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46720238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com