gpt4 book ai didi

javascript - 如何从客户端发送文件到http Node 服务器

转载 作者:行者123 更新时间:2023-12-01 00:44:59 25 4
gpt4 key购买 nike

我正在尝试将文件从 javascript 文件(客户端)发送到 Node 服务器。服务器正在接收请求,但是当我 console.log(request.body) 时,它返回未定义。我不知道为什么当我将文件发布到服务器时,该文件没有附加到 request.body 中。有人知道我做错了什么吗?

client.js(在浏览器中运行的 JavaScript)

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Dropzone from 'react-dropzone';

const request = require('request')


class App extends Component {

onDrop = (acceptedFiles) => {
request.post('http://localhost:8088', {
file: acceptedFiles[0]
}, (error, res, body) => {
if (error) {
console.error(error);
return
}
console.log(`statusCode: ${request.statusCode}`);
console.log(body);
})
}

render() {
return (
<Dropzone onDrop={this.onDrop}>
{({getRootProps, getInputProps, isDragActive}) => (
<div {...getRootProps()}>
<input {...getInputProps()} />
{isDragActive ? "Upload file" : 'Click me or drag a file to upload!'}
</div>
)}
</Dropzone>
);
}
}

export default App;
ReactDOM.render(
<App />,
document.getElementById('root')
);

server.js( Node 服务器)

const http = require('http');
var fs = require("fs");

const hostname = '127.0.0.1';
const port = 8088;

const server = http.createServer((request, response) => {
console.log(request.body);
if (request.method == 'POST') {
console.log('POST');
}
else {
console.log('GET');
response.statusCode = 200;
response.setHeader('Content-type', 'text/plain');
response.end('Node server');
}
});

server.listen(port, hostname, () => {
console.log('Server started on port ' + port);
});

最佳答案

您可以使用Filepond JavaScript文件上传库。查看它的文档 https://github.com/pqina/filepond

关于javascript - 如何从客户端发送文件到http Node 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57459765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com