gpt4 book ai didi

node.js - 类型错误 : server render is no a function

转载 作者:太空宇宙 更新时间:2023-11-04 00:29:06 24 4
gpt4 key购买 nike

我正在nodejs中运行服务器,但是当我尝试通过reactjs访问它时,我收到错误,因为 TypeError: (0 , _serverRender2.default) 不是函数。我该怎么办??

import config from './config';
import apiRouter from './api';
import express from 'express';
import path from 'path';
import sassMiddleware from 'node-sass-middleware';
import serverRender from './serverRender';

const server=express();
server.set('view engine','ejs');

server.use(sassMiddleware({
src:path.join(__dirname,'sass'),
dest:path.join(__dirname,'public')
}));

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

server.use(express.static('public'));

server.use('/api', apiRouter);

server.listen(config.port, () => {
console.info('express listening on port ', config.port);
});

这是我的服务器渲染文件

import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from './src/components/App';
import axios from 'axios';
//import config from './config';

const serverRender = () =>{

axios.get('http://localhost:8080/api/contests')
.then(resp=>{
return ReactDOMServer.renderToString(<App initialContests = {resp.data.contests}/>);
// console.log(resp.data);
});
}
export default serverRender;

最佳答案

serverRender() 不返回 Promise。您可以尝试基于回调的方法。

const serverRender = (callback) =>{
axios.get('http://localhost:8080/api/contests')
.then(resp=>{
callback(ReactDOMServer.renderToString(<App initialContests = {resp.data.contests}/>));
});
}

serverRender.js

server.get('/',(req,res)=> {
serverRender(content => {
res.render('index', {
content
});
});
});

关于node.js - 类型错误 : server render is no a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41714792/

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