Node.js API 在终端中返回 JSON,但不在浏览器中返回 JSON
Node.js API returns JSON in terminal but not in browser
有一个奇怪的问题。一直在寻找答案,但没有任何结果。我正在做一个节点 api 教程,当我执行任何 GET 请求时,它会从我的终端中的 mongoDB 数据库返回 JSON,但在我的浏览器或邮递员中我什么也没得到,只有在终端中我才得到任何响应。当我在邮递员中尝试开机自检时,它说它无法连接到后端。
这是我的代码:
var http = require('http');
var url = require('url');
var database = require('./database');
// Generic find methods (GET)
function findAllResources(resourceName, req, res) {
database.find('OrderBase', resourceName, {}, function (err, resources) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resources));
});
};
var findResourceById = function (resourceName, id, req, res) {
database.find('OrderBase', resourceName, {'_id': id}, function (err, resource) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
});
};
// Product methods
var findAllProducts = function (req, res) {
findAllResources('Products', req, res);
};
var findProductById = function (id, req, res) {
findResourceById('Products', id, req, res);
};
// Generic insert/update methods (POST, PUT)
var insertResource = function (resourceName, resource, req, res) {
database.insert('OrderBase', resourceName, resource, function (err, resource) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
});
};
// Product methods
var insertProduct = function (product, req, res) {
insertResource('OrderBase', 'Product', product, function (err, result) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(result));
});
};
var server = http.createServer(function (req, res) {
// Break down the incoming URL into its components
var parsedURL = url.parse(req.url, true);
// determine a response based on the URL
switch (parsedURL.pathname) {
case '/api/products':
if (req.method === 'GET') {
// Find and return the product with the given id
if (parsedURL.query.id) {
findProductById(id, req, res)
}
// There is no id specified, return all products
else {
findAllProducts(req, res);
}
}
else if (req.method === 'POST') {
//Extract the data stored in the POST body
var body = '';
req.on('data', function (dataChunk) {
body += dataChunk;
});
req.on('end', function () {
// Done pulling data from the POST body.
// Turn it into JSON and proceed to store it in the database.
var postJSON = JSON.parse(body);
insertProduct(postJSON, req, res);
});
}
break;
default:
res.end('You shall not pass!');
}
});
server.listen(8080);
console.log('Up and running, ready for action!');
您有几个回调,err
作为第一个参数,但您没有处理任何潜在的错误。这意味着如果出现问题,您不会捕获它并返回错误。我不知道这是否与此有关,但作为一种实践(甚至不是"最好的",而是一般的做法)而不是这样做
function (err, resource) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
}
这样做
function (err, resource) {
if(err){
// do something to warn the client and stop here
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
}
尝试一下,在尝试输出答案之前,看看您是否真的遇到了错误。
https://nodejs.org/api/http.html#http_response_end_data_encoding_callback
响应结束方法不将数据发送到响应套接字。也许你改变了它
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(resource));
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(resource));
res.end();
如果你想让套接字关闭做某事,你可以进入回调结束。
res.end(#logHandle());
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var connect = function (databaseName, callback) {
var url = 'mongodb://localhost:27017/' + databaseName;
MongoClient.connect(url, function (error, database) {
assert.equal(null, error);
console.log("Successfully connected to MongoDB instance!");
callback(database);
})
};
exports.find = function (databaseName, collectioName, query, callback) {
connect(databaseName, function (database) {
var collection = database.collection(collectioName);
collection.find(query).toArray(
function (err, documents) {
assert.equal(err, null);
console.log('MongoDB returned the following documents:');
console.dir(JSON.parse(JSON.stringify(documents)));
//console.dir(documents);
callback(null, documents);
}
)
database.close();
})
};
我想我们正在经历相同的教程,这是我的"数据库.js解决方案,对我有用。
相关文章:
- Jquery:对返回JSON数据的php脚本的Ajax调用
- 返回JSON中的下标
- jQuery Map 从多个源返回 JSON 对象
- 如何在 Node.js 中返回 JSON 后停止代码流
- AngularJS:表单提交没有返回JSON中的值
- 使用ajax发送数据,返回json
- 从我的解析函数返回json
- 如何从脚本页面返回json数据
- 有些人有任何关于如何使用Modified Java Script Value处理返回Json(url)的示例
- 如何在html页面中从ajax返回json数据
- Ajax调用在本地返回json,但在服务器上运行时返回xml
- ajax调用返回JSON ParseError即使认为JSON看起来是正确的
- 调用.ajax方法得到未定义的json结果,返回json格式列表<字符串>
- 如何通过C#返回JSON并用JavaScript进行解析
- 使用 AJAX 返回 json 数组
- 从 AJAX 命令返回 JSON 格式的响应
- 如何通过node中的请求返回JSON.js(从javascript)
- Node.js API 在终端中返回 JSON,但不在浏览器中返回 JSON
- 如何在支柱 2 中返回 JSON 数组
- Rhino:从 Java 中返回 JSON