我尝试使用PUT但仍然遇到404错误 ResourceNotFoundError:product / 1不存在 我对此很陌生,所以我不确切地知道我哪里出错了。请帮帮我,谢谢你。
server.js
var restify = require('restify');
var mongojs = require('mongojs');
var db = mongojs('mongodb://xxxxxx', ['products']);
var server = restify.createServer();
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.get("/products", function(req, res, next) {
db.products.find(function(err, products) {
res.writeHead(200, {
'Content-Type' : 'application/json; charset=utf-8'
});
res.end(JSON.stringify(products));
});
return next();
});
server.post("/product", function(req, res, next) {
var product = req.params;
db.products.save(product, function(err, data) {
res.writeHead(200, {
'Content-Type' : 'application/json; charset=utf-8'
});
res.end(JSON.stringify(data));
});
return next();
});
server.put("/product:id", function(req, res, next) {
db.products.findOne({
id: req.params.id
}, function(err, data) {
//merge req.params/product with the server/product
var updProd = {};
//logc similar to jquery.extend();
for(var n in data) {
updProd[n] = data[n];
}
for(var m in req.params) {
updProd[m] = req.params[m];
}
db.products.update({
id: req.params.id
}, updProd, {
multi: false
}, function(err, data) {
res.writeHead(200, {
'Content-Type' : 'application/json; charset=utf-8'
});
res.end(JSON.stringify(data));
});
});
return next();
});
server.listen(3000, function() {
console.log("Server started @ 3000");
});
module.exports = server;
client.js
var restify = require('restify');
var server = require('./server');
var client = restify.createJsonClient({
url : 'http://localhost:3000'
});
var testProduct = {
id: "1",
name: "Apple iPad AIR",
os: "iOS 7, upgradable to iOS 7.1",
chipset: "Apple A7",
cpu: "Dual-core 1.3 GHz Cyclone (ARM v8-based)",
gpu: "PowerVR G6430 (quad-core graphics)",
sensors: "Accelerometer, sgyro, compass",
colors: "Space Gray, Silver"
};
client.post('/product', testProduct, function (err, req, res, product) {
if (err) {
console.log("Create error ocurred >>>>>>");
console.log(err);
} else {
console.log('Create product >>>>>>>');
console.log(product);
}
});
testProduct.price = "1000";
client.put('/product/' + testProduct.id, testProduct, function (err, req, res, status) {
if (err) {
console.log("Update error ocurred >>>>>>");
console.log(err);
} else {
console.log('Update product >>>>>>>');
console.log(status);
}
});
client.get('/products', function (err, req, res, products) {
if (err) {
console.log("An error ocurred >>>>>>");
console.log(err);
} else {
console.log("Total products " + products.length);
console.log('All products >>>>>>>');
console.log(products);
}
});
答案 0 :(得分:4)
将server.js
中的行更改为/product/:id
。你遗漏了/
。