[英]Node/Express doesn't update the data model correctly
我已經按照本教程使用Nodejs和Mongo創建了一個寧靜的Api。 它工作正常,除了一些問題。 我的播放器型號是
var player = new mongoose.Schema({
name: String,
email: String,
score: String
});
當我嘗試通過Chrome / Firefox上的Postman擴展程序發布數據時,無法發布數據。 響應如下
"__v":0,"_id":"54fed7cf5dde9b1c1e90ed6c"}
但是,如果我通過終端發出請求
curl -XPOST http://localhost:3000/players -d 'name=ronaldo&email=ronaldo@com&score=232'
它工作正常。
除此之外,當嘗試發布或獲取Ajax請求時,即使添加了,我仍會收到CORS錯誤
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
// 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();
});
我也嘗試使用cors中間件,但沒有運氣。 該服務器在http://92.222.36.106:3000/players上運行,用於臨時測試。 隨時使用Postman發布數據。
set your cross origin request headers properly ,above you are accessing the request from "http://localhost:8888"(set it your domain) .it allows that domain only.Make sure your domain is properly set it or not .
It allows request from any origin
res.setHeader('Access-Control-Allow-Origin', '*');
It allows request from only "http://localhost:8888"
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
它似乎工作正常。 在郵遞員中檢查以下內容:
Content-Type
設置為application/json
raw
並選擇了JSON
。 以下是一些示例數據:
{“ name”:“ Mariano Rajoy”,“ email”:“ sobres.manila@pp.com”,“ score”:0}
如果那不起作用,這是一個有效的示例。 將其保存到.json文件並將其作為集合導入:
{"id":"d7fd0131-247a-08c0-4c89-5b46712201b8","name":"Players api","timestamp":1425989704352,"requests":[{"collectionId":"d7fd0131-247a-08c0-4c89-5b46712201b8","id":"2c301d19-62e6-6ad5-40bb-0fbec97305be","name":"http://92.222.36.106:3000/players/","description":"","url":"http://92.222.36.106:3000/players/","method":"POST","headers":"Content-Type: application/json\n","data":"{\n \"name\": \"Mariano Rajoy\",\n \"email\": \"sobres.manila@pp.com\",\n \"score\": 0\n}\n","dataMode":"raw","timestamp":0,"responses":[],"version":2}]}
(在您的代碼'Access-Control-Allow-Origin'中將其設置為' http:// localhost:8888 ',但是我假設您已經將其設置為'*',因為我將您的api與Postman一起使用)
編輯:
嘗試使用常規的ajax請求,但沒有成功。 顯然您的代碼中仍將"Access-Control-Allow-Origin"
設置為"http://localhost:8888"
而不是"*"
,並且Postman / Chrome應用程序可以繞過Cross Origin,這是不知道的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.