繁体   English   中英

节点/ Express无法正确更新数据模型

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM