禁用JavaScript后,NextJs对节点服务器的请求有错误

时间:2020-09-13 08:39:41

标签: javascript node.js reactjs express next.js

我的客户端应用程序是react js。我将nextjs用于ssr和redux。当Chrome javascript禁用时,我对服务器的请求有错误。

chrome dev tools

index.js页面

import Head from 'next/head'
import React from "react";
import GAppBar from "../components/appbar";
import {connect} from 'react-redux'
import {wrapper} from '../store/store'
import {reLogin} from "../store/actions/userAction";
import cookie from 'cookie'
import Fab from "@material-ui/core/Fab";
import AddIcon from '@material-ui/icons/Add';
import Router from "next/router";
import {getPost, getTopTenPost} from "../store/actions/postAction";
import GCard from "../components/card";
import Grid from "@material-ui/core/Grid";
import {Hidden} from "@material-ui/core";

function Home(props) {
    const {user, posts, topTenPosts} = props;

    return (
        <>
            <Head>
                <link rel="icon" href="/favicon.ico"/>
            </Head>
            <GAppBar/>
            {posts.length}
            {topTenPosts.length}
            <Grid container direction={"row"}>
                <Hidden smDown>
                    <Grid item xs={8}>
                        {
                            posts.map((item, index) => (

                                <GCard key={item._id} _id={item._id} fileType={item.fileType}
                                       title={item.title}
                                       summary={item.summary}
                                       subject={item.subject} filePath={item.filePath}
                                       comments={item.comments}
                                       creatorFilePath={item.creatorFilePath} description={item.description}
                                       likedByMe={item.likedByMe} bookmarkByMe={item.bookmarkByMe}/>


                            ))

                        }
                    </Grid>
                    <Grid item xs={4}>

                    </Grid>
                </Hidden>
            </Grid>
            <div>
                {
                    props.user.username
                        ?
                        <Fab onClick={event => Router.push('posts/create-post')} color={"primary"}
                             style={{position: 'absolute', bottom: 5, right: 5}}>
                            <AddIcon/>
                        </Fab>
                        :
                        <></>
                }
            </div>
        </>
    )
}

export const getServerSideProps = wrapper.getServerSideProps(async (ctx) => {
    const cookies = cookie.parse(ctx.req ? ctx.req.headers.cookie || "" : document.cookie);
    if (cookies.user) {
        const userObject = JSON.parse(cookies.user);
        await ctx.store.dispatch(reLogin(userObject));
        await ctx.store.dispatch(getPost('', ctx.store.getState().user.user.accessToken));
        await ctx.store.dispatch(getTopTenPost());
        return {
            props: {
                user: ctx.store.getState().user.user,
                posts: ctx.store.getState().post.posts,
                topTenPosts: ctx.store.getState().post.topTenPosts
            }
        }
    } else {
        await ctx.store.dispatch(getPost('', null));
        await ctx.store.dispatch(getTopTenPost());
        return {
            props: {
                user: {},
                posts: ctx.store.getState().post.posts,
                topTenPosts: ctx.store.getState().post.topTenPosts
            }
        }
    }

});


export default connect(null)(Home)

和postAction.js文件

import axios from "axios";
import * as types from '../types';
import {API_URL} from "../../utils/config";

export const getPost = (query, token) => async dispatch => {
    const res = await axios.get(`${API_URL}/api/post`, {
        "headers": {
            'Content-Type': 'application/json',
            'x-access-token': token
        }, params: {search: query}
    });
    dispatch({
        type: types.GET_POSTS,
        payload: res.data
    })
};
export const getTopTenPost = () => async dispatch => {
    const res = await axios.get(`${API_URL}/api/post/top-ten`, {
        "headers": {
            'Content-Type': 'application/json',
        }
    });
    dispatch({
        type: types.GET_TOP_TEN_POSTS,
        payload: res.data
    })
};

和nodejs服务器文件中的app.js

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const dbConfig = require("./config/db.config");
const app = express();


var corsOptions = {
    origin: "*"
};

app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: true}));


//database configs
const db = require("./models");
const Role = db.role;
db.mongoose
    .connect(`mongodb://${dbConfig.HOST}:${dbConfig.PORT}/${dbConfig.DB}`, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    .then(() => {
        console.log("Successfully connect to MongoDB.");
        initial();
    })
    .catch(err => {
        console.error("Connection error", err);
        process.exit();
    });

// simple route

require('./routes/follow.route')(app);
require('./routes/auth.route')(app);
require('./routes/users.route')(app);
require('./routes/post.route')(app);
require('./routes/upload.route')(app);
require('./routes/comment.route')(app);
require('./routes/like.route')(app);
require('./routes/bookmark.route')(app);

// set port, listen for requests
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}.`);
});


function initial() {
    Role.estimatedDocumentCount((err, count) => {
        if (!err && count === 0) {
            new Role({
                name: "user"
            }).save(err => {
                if (err) {
                    console.log("error", err);
                }

                console.log("added 'user' to roles collection");
            });

            new Role({
                name: "moderator"
            }).save(err => {
                if (err) {
                    console.log("error", err);
                }

                console.log("added 'moderator' to roles collection");
            });

            new Role({
                name: "admin"
            }).save(err => {
                if (err) {
                    console.log("error", err);
                }

                console.log("added 'admin' to roles collection");
            });
        }
    });
}

和postRoute.js文件

const controller = require("../controller/post.controller");
const { authJwt } = require("../middleware");
module.exports = function (app) {
    app.use(function (req, res, next) {
        res.setHeader('Access-Control-Allow-Methods', 'GET,POST, OPTIONS');
        next();
    });

    app.get(
        "/api/post",
        controller.getPost
    );
    app.get(
        "/api/post/top-ten",
        controller.getTopTenPosts
    );
    app.get(
        "/api/post/:postId",
        controller.getPostById
    );

    app.get(
        "/api/post/bookmark",
        controller.getMyBookmark
    );
    app.get(
        "/api/post/my",
        controller.getMyPost
    );
    app.get(
        "/api/post/target/:userId",
        controller.getTargetPost
    );

};

我说的是,启用javascript时没有任何问题,而禁用JavaScript时就会出现问题。

非常感谢

0 个答案:

没有答案