【发布时间】:2017-01-02 08:47:50
【问题描述】:
我想创建一个混合移动应用程序,其中后端是 Node js,它将数据保存在 mongodb 我的服务器正常工作我准备了处理用户请求的路由
我可以使用 GET 方法从我的服务器获取数据,但我的问题是我无法使用 POST 方法保存从 ionic 用户界面发送的数据。我尝试使用 POSTMAN 发送数据,数据已成功保存在 mongodb 中,但是当我从移动用户界面发送数据时出现问题
这是一张显示节点 js 服务器中使用 POSTMAN 发送 POST 请求的结果的图片 并从移动用户中发送 POST 请求
这就是数据在 mongoDB 中的保存方式
这是我在节点服务器中的路由文件
var Product = require('../models/product');
var express = require('express');
var router = express.Router();
router.route('/products')
.get(function(req, res) {
Product.find(function(err, products) {
if (err) {
return res.send(err);
}
res.json(products);
});
})
.post(function(req, res) {
console.log(req.body);
var product = new Product(req.body);
product.save(function(err) {
if (err) {
return res.send(err);
}
res.send({ message: 'product Added' });
});
});
这是表格
<label class="item item-input">
<input name="1" type="text" ng-model="product.nom" placeholder="nom du produit">
</label>
<label class="item item-input" >
<input name="2" type="text" ng-model="product.unite" placeholder="unité de cette produit">
</label>
...
<div class="item button button-block button-positive" ng-click="createProduct(product)" >
ajouter le produit
</div>
这是产品的控制者:
app.controller('productController', function($http, $scope) {
$scope.createProduct = function (new_prod){
console.log(new_prod);
var req = {
method: 'POST',
url: "http://localhost:3000/api/products",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: new_prod
};
$http(req)
.then(function(response) {
console.log(response);
});
};
【问题讨论】:
-
当你从 ionic 发帖时,回复是什么?
-
如果是 json,你为什么要使用 content-type
application/x-www-form-urlencoded发帖?试试application/json -
@Gonzalo Pincheira Arancibia 说该产品已添加但没有任何数据保存在 mongodb 中
-
使用 angular post 获取 JSON 服务器端,使用 postman 获取对象。很明显你用邮递员寄错了!
-
@Robbie 因为我用 x-www-form-urlencoded 对邮递员发布请求做同样的事情,并且数据已成功保存
标签: angularjs json node.js mongodb