【问题标题】:Connect node app and server + post image to server连接节点应用程序和服务器+将图像发布到服务器
【发布时间】:2021-05-06 19:55:09
【问题描述】:

我有一个关于节点应用程序的非常基本的问题,还有一个关于 HTTP 请求的问题。这是我第一次使用服务器创建节点应用程序,但我似乎无法让不同的组件一起工作。

这是我的 server.js

var express = require('express');
var multer = require('multer');
const request = require('request');

const upload = multer({dest: __dirname + '/uploads/images'});

const app = express();
const PORT = 3000;

app.use(express.static('public'));

app.post('/upload', upload.single('photo'), (req, res) => {
    if(req.file) {
        res.json(req.file);
    }
    else throw 'error';
});

app.listen(PORT, () => {
    console.log('Listening at ' + PORT );
});

然后我有一个带有运动检测系统的文件 app.js。每次检测到运动时,都会拍摄一张照片。这一切都很好。 然后应该将图片发送到服务器。这是我想不通的。 我创建了一个函数toServer(),它应该将检测到的数据发布到服务器

const request = require('request');    
function toServer(data) {
      const formData = {
      // Pass data via Buffers
      my_buffer: data,
      // Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
      // Use case: for some types of streams, you'll need to provide "file"-related information manually.
      // See the `form-data` README for more information about options: https://github.com/form-data/form-data
    
      };
      request.post({url:'http://localhost:3000/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
        if (err) {
          return console.error('Upload failed:', err);
        }
        console.log('Upload successful!  Server responded with:', body);
      });
    };

问题 1:在 localhost:3000 上运行 server.js 时,找不到 index.html 和我的 app.js 中加载的任何脚本。 问题 2:在 live-server 上运行 index.html 时,找到所有脚本,但我收到错误“未定义请求”。

我很确定我缺少一些基本的节点设置。 toServer() 的解决方案可能更复杂。

感谢您的宝贵时间, 芥末整形器

【问题讨论】:

    标签: javascript node.js http server


    【解决方案1】:

    问题一:

    这可能是因为您没有指定要呈现您的 index.html。 例如:

    res.render('index') 

    如果不是因为 upload.single('photo') 中的单引号,请尝试双引号。

    另一个可能的错误可能是您缺少默认的显示引擎设置。 一个例子:https://www.npmjs.com/package/hbs

    问题 2: 可能是因为你缺少标题

    var request = require('request');
    request.post({
      headers: {'content-type' : 'application/x-www-form-urlencoded'},
      url:     'http://localhost',
      body:    "example"
    }, function(error, response, body){
      console.log(body);
    });

    https://expressjs.com/查看更多信息

    【讨论】:

    • 感谢您的回答。你的建议并没有真正改变任何东西。你建议在哪里添加'res.render('index')'?
    • 这在很大程度上取决于您想要做什么,例如,如果您想在项目的主路径中显示一个视图,则 res.render('index') 将进入应用程序。 get('/' "这是你的逻辑和渲染");
    猜你喜欢
    • 1970-01-01
    • 2022-11-15
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    相关资源
    最近更新 更多