我已经按照Tutorial来创建一个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发布数据。
答案 0 :(得分:0)
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');
答案 1 :(得分:0)
似乎工作正常。在Postman检查:
Content-Type
设置为application/json
raw
,并且已选中JSON
。以下是一些示例数据:
{ “名字”:“Mariano Rajoy”, “email”:“sobres.manila@pp.com”, “得分”: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,但不知道......