发送后无法设置标题 – 通过NodeJs发布新用户
我正尝试使用Google Maps API , NodeJs , Express , MongoDB , Mongoose和AngularJS来构build应用程序,而我面临的问题是我无法解决查看其他相关SO Q / A的问题。
基本上,我试图post
到由username
和[latitude, longitude]
标识的我的db用户[latitude, longitude]
他们提交了我在我看来的某种forms。
当我尝试从Postman等应用程序直接post
用户时,一切正常,我可以在我的数据库中看到新用户。
相反,当我尝试直接发布用户提交时,我的控制台中出现以下错误:
/node_modules/mongodb-core/lib/topologies/server.js:766 catch(err) { process.nextTick(function() { throw err}); } ^ Error: Can't set headers after they are sent.
以及我的Google Chrome控制台中的以下日志:
angular.js:10695 GET http://localhost:3000/users net::ERR_CONNECTION_REFUSED
这是我的观点 :
<form name="addForm" novalidate> <div class="form-group"> <label for="username">Username <span class="badge">All fields required</span> </label> <input type="text" class="form-control" id="username" placeholder="OldandGold" ng-model="formData.username" required> </div> <div class="form-group"> <label for="latitude">Latitude</label> <input type="text" class="form-control" id="latitude" value="39.500" ng-model="formData.latitude" readonly> </div> <div class="form-group"> <label for="longitude">Longitude</label> <input type="text" class="form-control" id="longitude" value="-98.350" ng-model="formData.longitude" readonly> </div> <button type="submit" class="btn btn-danger btn-block" ng-click="createUser()" ng-disabled="addForm.$invalid">Submit</button> </form>
这是我的模式 :
// Pulls Mongoose dependency for creating schemas var mongoose = require('mongoose'); var GeoJSON = require('geojson'); var Schema = mongoose.Schema; var LocationSchema = new Schema({ name: {type: String, required: true}, location: { type: {type : String, required: true}, coordinates : [Schema.Types.Mixed] }, created_at: {type: Date, default: Date.now}, updated_at: {type: Date, default: Date.now} }); // Sets the created_at parameter equal to the current time LocationSchema.pre('save', function(next){ now = new Date(); this.updated_at = now; if(!this.created_at) { this.created_at = now } next(); }); // Indexes this schema in 2dsphere format (critical for running proximity searches) LocationSchema.index({location: '2dsphere'}); module.exports = mongoose.model('mean-locations', LocationSchema);
这是我的控制器的createUser函数 :
$scope.createUser = function($rootScope, $on) { // Grabs all of the text box fields var userData = { name: $scope.formData.username, location: { type: "Point", coordinates: [$scope.formData.latitude, $scope.formData.longitude] } }; console.log(JSON.stringify(userData)); // Saves the user data to the db $http.post('/users', userData) .success(function(data) { // Once complete, clear the form (except location) $scope.formData.username = ""; }) .error(function(data) { console.log('Error: ' + data); }); };
最后,这是我的路线 :
app.get('/users', function(req, res) { // Uses Mongoose schema to run the search (empty conditions) var query = User.find({}); query.exec(function(err, users) { if (err) res.send(err); // If no errors are found, it responds with a JSON of all users res.json(users); }); }); // POST Routes // -------------------------------------------------------- // Provides method for saving new users in the db app.post('/users', function(req, res) { // Creates a new User based on the Mongoose schema and the post body var newuser = new User(req.body); // New User is saved in the db. newuser.save(function(err) { if (err) res.send(err); // If no errors are found, it responds with a JSON of the new user res.json(req.body); }); });
使用我的Stringify Log
我能够看到一个正确的JSON:
{"name":"MyPoint","location":{"type":"Point","coordinates":["50.064","16.260"]}}
我对NodeJ很新,我不明白为什么会这样。
这是什么造成的? 我怎样才能解决这个问题?
提前致谢。
问题在这里,如果有错误,你必须停止执行。 (注意退货)。 例如,如果出现错误,代码将发送(res.send)错误,并继续执行res.json()
它将以您提到的错误结束,因为您已经设置了标题并发送响应。
newuser.save(function(err) { if (err) return res.send(err); // If no errors are found, it responds with a JSON of the new user res.json(req.body); });
“错误:发送后无法设置标头”。 错误通常表示您正在发送多个回复(使用快递)。
例如,这个代码将(尝试)在发生错误时发送两个响应
app.get('/users', function(req, res) { // Uses Mongoose schema to run the search (empty conditions) var query = User.find({}); query.exec(function(err, users) { if (err) res.send(err); // first response // If no errors are found, it responds with a JSON of all users res.json(users); // second response }); });
要解决这个问题,请确保在发送响应后退出:
app.get('/users', function(req, res) { // Uses Mongoose schema to run the search (empty conditions) var query = User.find({}); query.exec(function(err, users) { if (err) { res.send(err); return; // return here! } // If no errors are found, it responds with a JSON of all users res.json(users); }); });