React客户端尝试访问服务器资源而不访问它得到404

时间:2019-04-13 11:03:27

标签: reactjs client-server next.js

我相信我的反应代码在编译并发送到客户端后正在尝试访问服务器目录。这意味着当寻找gameLogic.js和style.css文件时,无法找到它们。我想知道如何使React组件即时工作以获取它们的副本并将其发送给远程客户端。我收到以下错误。

pages / game.js

import * as React from "react";
import Layout from "../components/Layout";
import Separator from "../components/Separator";
import CanvasCanvas from "../components/CanvasCanvas";

export default class extends React.Component {
    render() {

        return (
            <Layout>
                <main>
                    <div className="loginBox5">
                        <Separator height={50}/>
                        <div className="center">
                            <h1>Game Play:</h1>
                            <Separator height={50}/>
                            <div id="PlayAreaImg" className="gameContainer">
                                <CanvasCanvas id={"Memes"}/>
                            </div>
                        </div>
                        <Separator height={350}/>
                    </div>
                </main>
            </Layout>
        )
    }
}

src / gameLogic.js

var keyState = {};
window.addEventListener('keydown',function(e){
    keyState[e.keyCode || e.which] = true;
},true);
window.addEventListener('keyup',function(e){
    keyState[e.keyCode || e.which] = false;
},true);
x = 100;


function drawObj(ctx, object){
    var x = object[0];
    var y = object[1];
    var wid = object[2];
    var hei = object[3];
    var r = object[4];
    var g = object[5];
    var b = object[6];
    var t = object[7];
    // Renderer usage: Canvas context, x position, y position, object height, object width, red, green, blue, transparency
    ctx.fillStyle = "rgba("+String(r)+","+String(g)+","+String(b)+","+String(t)+")"; // colour ball
    ctx.fillRect (x, y, wid, hei); // render ball
    return ctx;
}


function renderAll(objects){
    console.log("### - Render: Starting - ###");
    for (var i = 0; i < objects.length; i++) {
        // Iterate over numeric indexes from 0 to 5, as everyone expects.
    }
    console.log("### - Render: Complete - ###");
}


//Define generic move function
function transformR(object, moveAmount, canvasHeight, canvasWidth){
    if (keyState[37]){
        object[0] -= moveAmount
        // console.log("left");
    }
    if (keyState[38]){
        object[1] -= moveAmount
        if (object[1] < 0){
            // console.log("Top Edge")
            object[1] = 0;
        }
        // console.log("up");
    }
    if (keyState[39]){
        object[0] += moveAmount
        // console.log("right");
    }
    if (keyState[40]){
        object[1] += moveAmount
        if (object[1] > (canvasHeight-object[3])){
            // console.log("Bottom Edge")
            object[1] = canvasHeight-object[3];
        }
        // console.log("down");
    }
    return object;
}


function transformL(object, moveAmount, canvasHeight, canvasWidth){
    if (keyState[65]){
        object[0] -= moveAmount
        // console.log("left");
    }
    if (keyState[87]){
        object[1] -= moveAmount
        if (object[1] < 0){
            // console.log("Top Edge")
            object[1] = 0;
        }
        // console.log("up");
    }
    if (keyState[68]){
        object[0] += moveAmount
        // console.log("right");
    }
    if (keyState[83]){
        object[1] += moveAmount
        if (object[1] > (canvasHeight-object[3])){
            // console.log("Bottom Edge")
            object[1] = canvasHeight-object[3];
        }
        // console.log("down");
    }
    return object;
}


function collisonDetect(ball, paddle){
    if (ball[0] < paddle[0] + paddle[2] &&
        ball[0] + ball[2] > paddle[0] &&
        ball[1] < paddle[1] + paddle[3] &&
        ball[3] + ball[1] > paddle[1]) {
        ball[8] = -ball[8];
        ball[9] = -ball[9];
        console.log("inside");
    } else {
        // console.log("not touching/inside");
    }
    return ball;
}




function ballMotion(height, width, ball, rightPaddle, leftPaddle){
    var x = ball[0];
    var y = ball[1];


    // collision detection
    ball = collisonDetect(ball, leftPaddle);
    ball = collisonDetect(ball, rightPaddle);
    var xSpeed = ball[8];
    var ySpeed = ball[9];
    x += xSpeed;
    y += ySpeed;

    // sides collison detection
    if (y <= 0){
        y = 0;
        ySpeed = -ySpeed;
    }
    if (y >= height-ball[2]) {
        y = height-ball[2];
        ySpeed = -ySpeed;
    }

    if (x <= 0) {
        x = 0;
        xSpeed = -xSpeed;
        leftPoints +=1
    }
    if (x >= width-ball[3]) {
        x = width-ball[3];
        xSpeed = -xSpeed;
        rightPoints +=1
    }


    // assign new values
    ball[0] = x;
    ball[1] = y;
    ball[8] = xSpeed;
    ball[9] = ySpeed;
    return ball;
}


function onPositionUpdate(position){
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    console.log("Current position: " + lat + " " + lng);
}


function onDown(event){
    cx = event.pageX;
    cy = event.pageY;
    console.log(cx, cy)
}

// Define objects as follows
// Renderer usage: Canvas context, x position, y position, object height, object width, red, green, blue, transparency
// Cut down usage: X, Y, height, width, red, green, blue, transparency
if (window.innerWidth < window.innerHeight) {
    ballDim = [window.innerWidth*.02, window.innerWidth*.02]
} else {
    ballDim = [window.innerHeight*.02, window.innerHeight*.02]
}
var ball = [window.innerWidth/2-((window.innerWidth*.02)/2), window.innerHeight*.8*.5-((window.innerHeight*.08)/2), ballDim[0], ballDim[1],200 ,200 ,200 ,3 , 3, 2];
var leftPaddle = [window.innerWidth*.01, window.innerHeight*.8*.5-((window.innerHeight*.08)/2), window.innerWidth*.01, window.innerHeight*.08, 0, 0, 200, 3];
var rightPaddle = [window.innerWidth*.8-(window.innerWidth*.01)-(window.innerWidth*.01), window.innerHeight*.8*.5-((window.innerHeight*.08)/2), window.innerWidth*.01, window.innerHeight*.08, 255, 100, 0, 3];
var leftPoints = 0;
var rightPoints = 0;

// Define gameLoop
function gameLoop(x,y) {
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(onPositionUpdate);
    } else {
        console.log("navigator.geolocation is not available");
    }
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    canvas.addEventListener("mousedown",onDown,false);

    var width = window.innerWidth*.8;
    var height = window.innerHeight*.8
    ctx.canvas.width = width;
    ctx.canvas.height = height;

    var moveAmount = 3;
    var motionTicker = + new Date()

    // console.log(motionTicker)
    // move checking function

    leftPaddle[0] = window.innerWidth*.01;
    rightPaddle[0] = window.innerWidth*.8-(window.innerWidth*.01)-(window.innerWidth*.01);

    leftPaddle = transformL(leftPaddle, moveAmount, height, width);
    rightPaddle = transformR(rightPaddle, moveAmount, height, width);

    ball = ballMotion(height, width, ball, rightPaddle, leftPaddle);

    ctx.save();
    ctx.clearRect(0,0,width,height);
    // Render objects in frame
    drawObj(ctx, ball);
    drawObj(ctx, leftPaddle);
    drawObj(ctx, rightPaddle);
    ctx.font = String(window.innerWidth*.05)+"px Arial";
    ctx.fillStyle = "white";
    ctx.fillText(String(rightPoints)+" - "+String(leftPoints), window.innerWidth*.333, window.innerHeight*.1);
    ctx.restore();

    setTimeout(gameLoop, 1);
    await this.forceUpdate();
    this.state = {motionTicker}
}

/components/CanvasCanvas.js

import * as React from "react";

export default class extends React.Component {

    render() {
        return (
            <canvas ref={"canvas"} id = {"canvas"} width={640} height={425}/>
        )
    }


    async componentDidMount() {
        const script = document.createElement("script");
        console.log("ln14")
        script.src = "../src/gameLogic.js";
        script.async = true;
        // console.log(script);
        document.head.appendChild(script);
        console.log(script);

        await this.setState(
            {
                text: this.props.text,
                ...this.state
            }
        );
        await this.forceUpdate();
        const canvas = this.refs.canvas;
        const ctx = canvas.getContext("2d");
        ctx.fillText((this.state && this.state.text) ? this.state.text : "Not initialised (nullcheck)", 210, 75);
    }
}

预期结果是gameLogic js文件将其输出呈现在canvas元素内,并在每个“帧”的末尾强制更新它。 实际结果是一串404,如下所示:

http://localhost:3000/css/style.css net::ERR_ABORTED 404 (Not Found)
index.js:1 Warning: Extra attributes from the server: deluminate_imagetype
GET http://localhost:3000/src/gameLogic.js net::ERR_ABORTED 404 (Not Found)

感谢您事先提供的帮助。

1 个答案:

答案 0 :(得分:1)

如果要在编译后访问这些文件,请将它们放在static文件夹中,例如script.src = "/static/gameLogic.js"

或使用动态导入

import dynamic from 'next/dynamic'
const gameLogic = dynamic(() => import(`../src/gameLogic.js`))

dynamic-import doc