无法使用PUT方法通过CORS使用Express发送数据

时间:2017-11-05 21:47:50

标签: http express cors

我正在使用端口8080上的RESTful API在端口4000上创建简单的Web应用程序。我使用cors包进行Express设置,我似乎从OPTIONS请求发回正确的标头,请参阅下文:

X-Powered-By: Express
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Vary: Access-Control-Request-Headers
Access-Control-Allow-Headers: content-type
Content-Length: 0

返回状态为204 ok。然后我在FF网络控制台中看到PUT请求,大约45秒后出现请求标题:

PUT /movies/updatemovie/59f4ee92be4becd967a573ca HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
Referer: http://localhost:4000/movies
Content-Length: 151
Origin: http://localhost:4000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

请求参数为:

documentID=59f4ee92be4becd967a573ca&title=Captain%20America%3A%20Civil%20UnWar&release=2016&score=9&reviewer=%20Janet%20Garcia&publication=%20MoviesNow

Chrome显示PUT在4分钟后失败。

数据没有发布到Mongo,也没有得到服务器的任何响应。

以下是相关代码:

网络应用

$(".panel").each(function (index) {
    if ($(this).find("input[name = 'update']").is(":checked")) {
        updatedDocument = {
            documentID: $(this).data("id"),
            title: $(this).find("input#name").val(),
            release: $(this).find("input#release").val(),
            score: $(this).find("input#score").val(),
            reviewer: $(this).find("input#reviewer").val(),
            publication: $(this).find("input#publication").val()
        };
        JSON.stringify(updatedDocument);
        console.log(Object.values(updatedDocument));
    } // end if
}); // .each

// Now we have the document stored in JSON object, so lets form 
// an AJAX req and grab the updated data from our document and send
// a PUT to our API endpoint
$.ajax({
    type: 'PUT',
    data: updatedDocument,
    url: 'http://localhost:8080/movies/updatemovie/' + updatedDocument.documentID,
    dataType: 'JSON',
    contentType: 'application/json'
}).done(function (response) {
    // Check for successful (blank) response
    if (response.msg === '') {
        // do nothing
    }
    else {
        alert('Error: ' + response.msg);
    }
}); // end .done

API

/*
 * Put to Update movie.
 */
router.options('updatemovie/:id', cors());  
router.put('/updatemovie/:id', cors(), function(req, res) {
    const db = req.db;
    console.log(req.params.id);
    console.log(req.body.publication);

    const movieCollection = db.get("movies");
    const movieToUpdate = req.params.id; // Assign collection document id from url :id value
    const movieTitle = req.body.title;
    const movieRelease = req.body.release;
    const movieScore = req.body.score;
    const movieReviewer = req.body.reviewer;
    const moviePublication = req.body.publication;

     // Update the movie document from PUT info
    movieCollection.update({'_id' : movieToUpdate}, 
        {
            $set: {
              title: movieTitle,
              release: movieRelease,
              score: movieScore,
              reviewer: movieReviewer,
              publication: moviePublication
            }
        },
        function(err)  {
            res.send((err === null) ? {msg: ''} : {msg: err});
        }); // movieCollection .update

});

我从API中的console.logs中得不到任何结果。任何建议最受欢迎。

更新:通过从APP contentType: application/JSON删除行,现在一切正常。我以为我想将数据作为JSON发送到我的API?任何有任何想法或意见的人都欢迎。

1 个答案:

答案 0 :(得分:1)

您不是以JSON格式发送数据。您已将content-type标头设置为application/json,但数据仍将编码为application/x-www-form-urlencoded。要使用jQuery发送JSON数据,您需要自己编码:

data: JSON.stringify(updatedDocument),

在服务器上,您需要一个合适的bodyParser配置:

app.use(bodyParser.json());

或:

app.use(express.json());

当您删除该标题回归到其默认值contentType: 'application/json'的行application/x-www-form-urlencoded时。这与数据的格式相匹配,并且可能已配置app.use(bodyParser.urlencoded())app.use(express.urlencoded())来解析该数据。由于您的数据是扁平字符串/字符串数据结构,因此您选择的格式并不重要,您最终会在res.body中得到相同的值。