Disculpe cualquier uso incorrecto de términos o palabras, todavía estoy tratando de entender Node.js.
Estoy ejecutando un sitio web con LiveServer y un servidor Node.js en la misma PC. Me doy cuenta de que podría estar ejecutando el sitio web como una aplicación Node.js, pero estoy tratando de usar POST con Fetch para enviar un archivo desde el sitio web al servidor.
El servidor manejará la copia de archivos y tal vez algunas otras cosas que me parezcan interesantes, pero por ahora eso es todo.
El problema es que ni siquiera puedo conectarme a localhost. LiveServer se ejecuta en el puerto 5501 y el servidor Node en el puerto 5000.
A continuación se muestra el código para el archivo index.js para el sitio web, solo toma un evento de arrastrar y soltar e intenta enviar el archivo a localhost: 5000:
var file = event.dataTransfer.items[i].getAsFile(); console.log('... file[' + i + '].name = ' + file.name); var data = new FormData(); data.append('file', file); const url = new URL('http://localhost:5000/'); fetch(url, { method:'POST', body: data }) }Y aquí está el código del servidor Node.js:
const express = require('express'); //Import the express dependency const cors = require('cors'); const app = express(); //Instantiate an express app, the main work horse of this server const port = 5000; //Save the port number where your server will be listening //setting middleware app.use('/dist', express.static('dist')); app.use(cors({ allowedOrigins: [ 'http://localhost:5000' ] })); // //Idiomatic expression in express to route and respond to a client request // app.get('/', (req, res) => { //get requests to the root ("/") will route here // res.sendFile('src/index.html', { root: __dirname }); //server responds by sending the index.html file to the client's browser // //the .sendFile method needs the absolute path to the file, see: https://expressjs.com/en/4x/api.html#res.sendFile // }); app.listen(port, () => { //server starts listening for any attempts from a client to connect at port: {port} console.log(`Now listening on port ${port}`); }); app.post('http://localhost:5000/', function (req, res) { // const body = req.body.Body // res.set('Content-Type', 'text/plain') // res.send(`You sent: ${body} to Express`) res.sendFile('src/index.html', { root: __dirname }); //server responds by sending the index.html file to the client's browser })El error que recibo en Chrome es: POST http://localhost:5000/ 404 (Not Found)
¿Es posible lo que estoy tratando de hacer? Probé diferentes variaciones de escribir la URL y aún recibo el mismo mensaje de error. Google tampoco es útil.
Cualquier ayuda se agradece, gracias por adelantado.
El primer argumento en app.METHOD debe ser la ruta para la cual se invoca la función de middleware; puede ser cualquiera de:
Entonces, por lo tanto, esta línea
app.post('http://localhost:5000/', ...)tiene que ser solo un nombre de ruta, así que reemplácelo con este
app.post('/', ... )