【问题标题】:Upload images with ajax and nodejs using Formdata - CORS error issue使用 Formdata 上传带有 ajax 和 nodejs 的图像 - CORS 错误问题
【发布时间】:2020-07-24 20:08:35
【问题描述】:

我正在使用 vanilla javascript (AJAX) 发布表单并使用 Formdata()。表单的提交被nodejs捕获并连接数据库。

问题是当我向 nodejs 发送正常数据时,我能够连接数据库并响应成功。但是,当我添加文件上传输入(以存储文件路径)并尝试连接时,CORS 错误即将到来。我已在 express(nodejs) 中将允许跨源的标头设置为 * 值。

HTML:

          <div class="form-group">
            <label for="textareaLbl2">Description 2</label>
            <textarea  name="descr2" class="form-control" id="textareaLbl2" rows="3"></textarea>
          </div>
          <div class="form-group">
            <label for="img">Upload:</label>
            <input type="file" name="img" class="form-control" id="img" />
          </div>

JS:

testForms.onsubmit = function(event) {
    event.preventDefault();
    var formData = new FormData(testForms);
    request.open( "POST", "https://xyz.domain.com/addList", true);
    request.send(formData);
}

Nodejs:

app.use(function (req, res, next) {
    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    这行得通吗?如果没有,您是否尝试过 cors 中间件: https://www.npmjs.com/package/cors

     app.use(function (req, res, next) {
    
        // Website you wish to allow to connect
        res.setHeader('Access-Control-Allow-Origin', '*');
    
        // Request methods you wish to allow
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    
        // Request headers you wish to allow
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    
        // Set to true if you need the website to include cookies in the requests sent
        // to the API (e.g. in case you use sessions)
        res.setHeader('Access-Control-Allow-Credentials', true);
    
        // Pass to next layer of middleware
        next();
    });
    

    还可以尝试在节点端设置 Content-Type。

    【讨论】:

    • cors 错误中是否有更多细节,您是否尝试过使用邮递员等。也许尝试在 .send() xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest '); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    猜你喜欢
    • 2017-05-25
    • 1970-01-01
    • 2015-04-23
    • 2023-03-12
    • 2016-06-24
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 2016-08-02
    相关资源
    最近更新 更多