Using a simple express server, I am hosting an html file that contains a form and input tag, allowing a user to upload images. Main.js (linked to index.html) processes and sends said file to upload.php which would move the image to an uploads directory. When the fetch api calls for upload.php POST https://localhost/upload.php 404 (Not Found) is thrown. Directly accessing https://localhost/upload.php downloads upload.php to my downloads directory.
server.js:
const express = require("express");
const https = require("https");
const path = require("path");
const fs = require("fs");
const ip = require("ip");
var app = express();
//current dir
const CWD = __dirname;
var clientIp;
var port = 443;
function getIp(req, res, next) {
clientIp = req.ip;
console.log("ip:" + clientIp);
next();
}
app.use(getIp);
app.use(express.static(CWD + "/public/"), function (req, res, next) {
next();
});
app.get("/"),
function (req, res, next) {
res.sendFile(path.join(CWD + "index.html"));
};
//https certificate and key
var sslServer = https.createServer(
{
key: fs.readFileSync(path.join(CWD, "certificate", "key.pem")),
cert: fs.readFileSync(path.join(CWD, "certificate", "certificate.pem")),
},
app
);
sslServer.listen(port, function () {
console.log("listening on" + port);
console.log("CTRL + C to exit server");
});
Display More
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css" />
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form class="form" id="imgForm">
<input type="file" id="inputImg"></input>
<button type="submit">Upload Image</button>
</form>
<script src="main.js"></script>
</body>
</html>
Display More
main.js:
const imgForm = document.getElementById("imgForm");
const inputImg = document.getElementById("inputImg");
imgForm.addEventListener("submit", (e) => {
e.preventDefault();
const endpoint = "upload.php";
const formData = new FormData();
formData.append("inputImg", inputImg.files[0]);
//fetch request to upload.php
fetch(endpoint, {
method: "post",
body: formData,
}).catch(console.error);
});
Display More
upload.php:
<?php
//moves uploaded file to uploads dir
$targetPath = "uploads/" . basename($_FILES["inputImg"]["names"]);
move_uploaded_file($_FILES["inputImg"]["tmp_name"], $targetPath);
Index.html, main.js and upload.php are all in the same "/public" directory. As evident by https://localhost/upload.php downloading upload.php, are also able to be accessed. My goal is for the upload.php to run and succesfully move inputImg.files[0] into the /uploads directory. If somebody recognizes what I am doing wrong I would appreciate a gesture in the right direction.