简体   繁体   中英

Accessing server-side text file using JavaScript

I am making a website for students to give test... I will be also hosting it. But I want to make the code such that a particular student can give the test only once a day. So, I thought of placing a text ( .txt ) file on the server and read and write the dates, the student last gave the test. But, I came to know about the fact that JavaScript cannot access server-side files. So, is there a way to do the thing I want to?

Note : I want to do both reading and writing into the file

You'll need to use a client-server model:

  • Client makes a HTTP request to the server
  • Server receives the request and reads the file on behalf of the client

Here's a bare-bones example in express:

import express from 'express';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import level from 'level';

const app = express();
app.use(cookieParser());

const {Level} = level;
const lastTakenDates = new Level('lastTakenDates', {valueEncoding: 'json'});

const jsonParser = bodyParser.json();

app.post('/start', jsonParser, async (request, response) => {
    const username = somehowGetUsername(request.cookies.session);
    const now = Date.now();

    const lastTaken = await lastTakenDates.get(username);

    if (!lastTaken || (lastTaken + 1000 * 60 * 60 * 24) < now) {
        await lastTakenDates.put(username, now);
        response.status(200).send("OK");
        return;
    }

    response.status(403).send("You can only take the quiz once a day");
});

I am answering my question because I found a very easy way to accomplish the task. Its just simply easy to use PHP. You can write a simple PHP script for handling the file and then activate that script using an AJAX request which can be posted through JQuery. The text to be written can be set as a cookie using javascript and that cookie will be accessed through PHP and the task will be accomplished !!!!

Also, a big thanks to all the sincere effortsof @Richie Bendall to help me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM