I am having a 404 issue with my NodeJS API. I don't know if I am quite doing it right, I tried referring to documentation, and I feel like it's close.
MongoDB Schema
var User = mongoose.Schema({
local: {
email: String,
password: String,
handle: String,
pic: {data: Buffer, contentType: String}
}
});
NodeJS UPDATE API
app.post('/api/users', function(req, res, user) {
User.update({email : user.email,
password : user.password,
handle : user.handle,
pic : user.pic},
{$set: {
email : req.body.email,
password : req.body.email,
handle : req.body.handle,
pic : req.body.pic,
done : false
}
}, function(err, users) {
if(err) {
res.send(err);
}
res.redirect('/profile');
});
});
Controller POST API call
$scope.editProfile = function() {
$http.post('/api/users', $scope.editFormData)
.success(function(data) {
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
Any suggestions?
You are not doing a post call correct. You can't pass your post object in the URL. Your node post should look like this.
app.post('/api', upload.array(), function(req, res) {
var body = req.body; //body will be your post object
});
For a post to work you need to make sure you have the proper things added to your Node Project. The above example is using ExpressJS with require('body-parser') and require('multer'). The example you are showing will never show as a true path. For reference here is how you would do a get in node.
app.get('/getcall/*', function(){
// the * denotes any singleton parameter you wanted to pass in.
})
Here are the references I use in all my node projects. These are the basics.
var express = require('express'),
bodyParser = require('body-parser'),
multer = require('multer'),
helmet = require('helmet'),
upload = multer(),
path = require('path'),
request = require('request'),
app = express(),
http = require('http');
Also as for your angular call an $http.post looks like this and you should be using .then instead of .success.
$http.post('/api', $scope.editFormData)
.then(function successCallback(resp) {
console.log(resp.data)
}, function errorCallback(resp) {
console.log(resp)
});
Related
I am using "$http.get" for send request. My API response in browser, it returns what i want. But in Ionic App, it return HTML body tag text.
My Code is:
var params = {
email: 'test#gmail.com',
password: '123'
}
$http.get("https://www.nepalivivah.com/API/index.php/accessapi/loginapi", { params: params }).then(function (data) {
alert(JSON.stringify(data));
}).error(function (data) {
alert(JSON.stringify(data));
});
This is my AngularCode. When i run it in postman, it return valid response. But in Ionic App not Working.
If you want the $http.get, this should work.
var params = {
email: 'test#gmail.com',
password: '123'
}
$http.get("https://www.nepalivivah.com/API/index.php/accessapi/loginapi").then(function (data) {
alert(JSON.stringify(data));
}).error(function (err) {
alert(JSON.stringify(err));
});
However, in this case, what you are trying to do is to login into something. A get request will not work with this. You need to use $http.post at least in this case.
I'm making an ionic app for android and today I implemented a server side nodejs (express) Restful API with mongodb on cloud9.
But when I trigger a http request to the url, I keep getting the error mentioned in the title:
This is my angular http request on ionic (simply to test first):
app.controller('DashCtrl', function($scope, $http, $q) {
$http.get('https://[workspace]-[user].c9users.io/api/capture')
.then(function(result) {
console.log(result);
});
});
This is an image of my workspace:
I used the following code to make the database:
api.js
var Capture = require('../models/capture');
module.exports = function(router) {
router.get('/capture', function(req, res){
var capture = new Capture();
// capture.birdname = req.body.birdname;
// capture.place.city = req.place.body.city;
// capture.place.country = req.place.body.country;
capture.birdname = "Pigeon";
capture.save(function(err, data){
if(err)
throw err;
res.json(data);
});
});
router.get('/captures', function(req, res){
Customer.find({}, function(err, data){
res.json(data);
})
})
}
capture.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var captureSchema = mongoose.Schema({
birdname: String,
place: {
city: String,
country: String
}
});
module.exports = mongoose.model('Capture', captureSchema)
database.js
module.exports = {
'url': 'mongodb://' + process.env.IP
}
server.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var configDB = require('./server/config/database.js');
mongoose.connect(configDB.url);
var api = express.Router();
require('./server/routes/api')(api);
app.use('/api', api);
app.listen(process.env.PORT, process.env.IP);
console.log('Listening on port ' + process.env.PORT)
Anyone have an idea why I'm getting this error and what I need to do to fix this?
I'm guessing it has something to do with the server allowing me to send requests to the API though I don't know how to implement that.
Is there also a way to secure my database (API key maybe) and how would I implement this?
Thanks in advance
var awsSdk = require('aws-sdk');
awsSdk.config = {
"accessKeyId": "key",
"secretAccessKey": "secret",
"region": "us-east-1"
}
var s3 = new awsSdk.S3({
accessKeyId: 'key',
secretAcessKey: 'secret'
});
exports.awsDelete = function(req, res){
s3.deleteObject({
Bucket: 'bucket',
Key: req.body.photo
}, function(err,data){
if (err) console.log('delete err', err);
console.log(data);
});
};
I can't figure out how to make this work (yet).
initially, I was getting a "no config" error, so I added the awsSdk.config json above. Now, it's just getting hung / pausing with no error. I am getting the expected key in req.body.photo.
My hunch is that i'm missing something in my config..
What am I missing / screwing up?
Update
I've added the code suggested below, but still no luck. I'll show how i'm passing my parameter:
updated code from answer below:
'use strict';
var aws = require('./aws');
var amazon = require('aws-sdk');
amazon.config = new amazon.Config();
amazon.config.accessKeyId = aws.key;
amazon.config.secretAccessKey = aws.secret;
amazon.config.region = aws.region;
var s3 = new amazon.S3();
exports.awsDelete = function(req, res){
var params = {
Bucket: aws.bucket,
Key: res.body.photo
};
s3.deleteObject(params, function(err, data) {
if (err) console.log(err)
else console.log("Successfully deleted myBucket/myKey");
});
};
route:
app.post('/awsDelete', uploads.awsDelete);
Front end Angular:
factory:
angular.module('clientApp').factory('Uploads', function($http) {
return {
delete: function(data){
console.log('delete fired');
return $http.post('/awsDelete', data);
}
};
});
angular controller:
angular.module('clientApp').controller('Distiller-editCtrl', function(Uploads){
$scope.item = {}
$scope.delete = function(){
Uploads.delete($scope.item).then(function(res){
console.log(res)
});
};
});
Seems it 'sort of works'. But something is making it take an extremely long time:
POST /awsDelete 200 120007ms
If I refresh the page, that causes it to successfully delete it as well.
Does anyone notice anything in my code that could be causing such a long response time.
Also, not getting the "successfully completed" console.log
I just tested this in node and it worked fine, obviously you need to put in your own accesskey, secretaccesskey, bucket and bucket key:
var AWS = require('aws-sdk');
AWS.config = new AWS.Config();
AWS.config.accessKeyId = "";
AWS.config.secretAccessKey = "";
AWS.config.region = "us-east-1";
var s3 = new AWS.S3();
var params = {
Bucket: 'test537658ghdfshgfd',
Key: '1.png'
};
s3.deleteObject(params, function(err, data) {
if (err) console.log(err)
else console.log("Successfully deleted myBucket/myKey");
});
Alternatively you can use Minio-Js client library, its Open Source and compatible with AWS S3.
Below is remove-object.js example, you can find complete list here
var Minio = require('minio')
var s3Client = new Minio({
endPoint: 's3.amazonaws.com',
accessKey: 'YOUR-ACCESSKEYID',
secretKey: 'YOUR-SECRETACCESSKEY'
})
// Remove an object name my-objectname.
s3Client.removeObject('my-bucketname', 'my-objectname', function(e) {
if (e) {
return console.log(e)
}
console.log("Success")
})
Please replace YOUR-ACCESSKEYID and YOUR-SECRETACCESSKEY with your own also replace the endPoint to the one you have your bucket is created.
us-east-1: 's3.amazonaws.com',
us-west-1 : 's3-us-west-1.amazonaws.com',
us-west-2 : 's3-us-west-2.amazonaws.com',
eu-west-1: 's3-eu-west-1.amazonaws.com',
sa-east-1: 's3-sa-east-1.amazonaws.com',
eu-central-1: 's3-eu-central-1.amazonaws.com',
ap-southeast-1: 's3-ap-southeast-1.amazonaws.com',
ap-southeast-2: 's3-ap-southeast-2.amazonaws.com',
ap-northeast-1: 's3-ap-northeast-1.amazonaws.com'
Installing Monio-js
$ npm install --save minio
Hope it helps.
Disclaimer: I work for Minio.
I´m making an angular application, which gives users the possibilities, to manage their projects. I´ve got nodeJS & express serveside and MongoDB as my database.
I want to achieve, that a user can upload media(images under 16MB, so no need to use GridFS) to their projects and that you can display which project, has which media attached.
I´m not getting the images, nor an error. How can I pass the project_Id from angular, to my route, to find the media attached to the project? Is this way of trying to POST and GET the media the right way?
The model for projects and for media:
var mediaSchema = mongoose.Schema({
media : {data: Buffer, contentType: String},
project_id : String,
updated_at : {type: Date, default: Date.now }
});
var projectSchema = mongoose.Schema({
author : String,
name : String,
description : String,
tags : String,
updated_at : {type: Date, default: Date.now },
active : {type: Boolean, default: false}
});
The routing
var Media = require('./models/media.js');
//GET all the media
app.get('/uploads/', function(req, res, next){
Media.find(function (err, media){
if (err) return next (err);
res.json(media);
});
});
//GET one item
app.get('/uploads/media/:projectId', function(req, res, next){
Media.findOne(req.params , function (err, media){
if (err) return next (err);
res.json(media);
});
});
Managing the uploads
app.use(multer({ dest: './uploads/',
rename: function (fieldname, filename) {
return filename+Date.now();
},
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
done=true;
}
}));
var Media = require('./app/models/media.js');
//POST media to the upload directory
app.post('/uploads/', function(req, res){
if(done==true){
Media.create(req.body, function(err, post){
console.log(req.files);
res.end('File uploaded');
});
}
});
Angular Controller
var app = angular.module('myApp', []);
app.controller('projectCtrl', function($scope, $http) {
$scope.myVar = false;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar
};
$http.get('/profile/project/').then(function (res){
$scope.projects = res.data;
});
//GET Media
var projectId = {{projects._id}};
$http.get('/uploads/media' + projectId).succes(function(data){
console.log('Medien-Daten erhalten');
$scope.media = data;
});
});
Kind regards from Germany,
David
Update (new Errors)
Trying to implement a solution, I get problems with my scopes. When I´m adding the $http.get for the media, my other scope seem to fetch no data... they are shown like this:
Update 2(scope error fixed)
Fixed the error in the controller. I hadn´t defined a var for projectId, that caused the error.
Managed to make the GET request work, and my application is looking for entries in the database. But i can´t manage to see any..
Your use of .find is incorrect in the get all function.
See http://mongoosejs.com/docs/api.html#query_Query-find
Media.find({}, function (err, media){
if (err) return next (err);
res.json(media);
});
This will return all documents.
$http.post('/#/college', $scope.userb)
.success(function(data, status) {
console.log("Sent ok");
})
.error(function(data, status) {
console.log("Error");
})
[1]: http://i.stack.imgur.com/NlHyy.jpg
Is this the correct format/way to post my form data using http.post.?
The above code always returns "error" in the console.
please guide me to use http.post to post my form datathrough my controller.
var nodemailer = require("nodemailer");
var bodyparser = require("body-parser");
var app = express();
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "abc#gmail.com",
pass: "abc202"
}
});
var rand, mailOptions, host, link;
app.get('/#/college',function(req,res){
rand=Math.floor((Math.random() * 100) + 54);
host=req.get('host');
link="http://"+req.get('host')+"/verify?id="+rand;
mailOptions={
to : req.userb.counselloremail,
subject : "Please confirm your Email account",
html : "Hello,<br> Please Click on the link to verify your email.<br>Click here to verify"
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
app.use(morgan('dev'));
app.use(gzippo.staticGzip("" + __dirname + "/dist"));
app.listen(process.env.PORT || 5000);
I am trying to access the email address from the scope variable and post it so that i may send a confirmation mail that he is successfully registered now. Also I am sending the code of my web.js file that receives the posted data and sends the mail.
That URL you are posting to is not going to be valid.
If you are posting to another route in your app, the URL would just be #/college.
I'm also a little worried that you don't have anything setup to receive a post request, like on a server or anything. Could you give some more detail about what you are trying to do and your setup?
var dataObject = {
userid : LoginUserID
};
var responsePromise = $http.post(ApiAccessUrl+"/store/userstoreslist/", dataObject, {});
responsePromise.success(function(dataFromServer, status, headers, config)
{
var outputDate=angular.fromJson(dataFromServer);
});
responsePromise.error(function(data, status, headers, config) {
console.log("Error in fetching user store call!");
});
This is the correct way of sending data using http.post