I am trying to use Angular's POST and PUT methods but I keep getting the error:
Response for preflight has invalid HTTP status code 404
My code:
$http({
method: "POST",
url: "http://localhost:4567/api/v1/project",
data: project_data
}).then(function successCallback(response) {
console.log(response);
}),
function errorCallback(response) {
console.log('error!');
console.log(response);
}
$http({
method: "PUT",
url: "http://localhost:4567/api/v1/project/1",
data: data
}).then(function successCallback(response) {
console.log(response);
}),
function errorCallback(response) {
console.log('error!');
console.log(response);
}
Does anyone know what might be going on or how to fix it? Other solutions I've found involve changes to the server side code (in this instance, I don't have access to the server). Thanks in advance!
If you use Node.js, just do this:
app.options('/api/v1/project/1', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("Content-Type", "application/json;charset=utf-8");
res.status(204);//important
res.end()
});
app.put('/api/v1/project/1', function(req, res, next) {
...your normal code here
})
Related
This is my controller for the time being
.controller('HotelsController', ['$http', HotelsController]);
function HotelsController($http) {
var vm = this;
$http({
method: 'GET',
url: '/api/hotels'
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
}
but I get an error message
CAN'T GET /api/hotels
and this is my api
module.exports.hotelsGetAll = function (req, res) {
Hotel
.find()
.skip(offset)
.limit(count)
.exec(function (err, hotels) {
if (err) {
res
.status(500)
.json(err);
} else {
console.log("Found Hotels ", hotels.length);
res
.json(hotels);
}
})
};
any suggestions please?
You should append your api host url before performing http request.
Edit your controller:
.controller('HotelsController', ['$http', HotelsController]);
function HotelsController($http) {
var vm = this;
$http({
method: 'GET',
url: 'http://yourhostapiurl/api/hotels' //Append the url of your api
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
}
Thank you for helping me!
In addition I added these lines of codes in my server(app.js) file
app.all("/api/*", function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
return next();
});
I want to post data from Angular and save it in MongoDB through Express and Mongoose.
myConfig file
'use strict';
var express = require('express');
var parser = require('body-parser');
var router = require('./api');
var app = express();
require('./database');
app.use('/', express.static('public'));
app.use(parser.urlencoded({extended: true}));
app.use(parser.json());
app.use('/api', router);
app.listen(3000, function () {
console.log("Evalyst is running on port 3000");
});
myController
$scope.addNewEvaluation = function (newEvaluation) {
dataService.addNewEvaluation(newEvaluation);
$scope.closeModal();
};
MyService
$http({
method: 'POST',
url: 'http://localhost:3000/api/evaluations',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {'evaluation': newEvaluation}
}).success(function (data) {
console.log(data);
}).error(function(data){
console.log(data);
});
};
My backend (node.js, express, mongoose)
router.post('/evaluations', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
var evaluation = req.body;
console.log(evaluation);
Evaluation.create(evaluation, function (err, evaluation) {
if (err) {
return res.status(500).json({message: err.message});
}
res.json({evaluation, message: "Evaluation created"});
});
});
The problem is that an empty object is saved in my MongoDB.
In my req.body, I have the following line:
body: { '{"evaluation":{"title":"Sports","description":"Just do it","notifFreq":"daily"}}': '' },
I don't understand why I get the evaluation wrapped in {' }' : ''}.
Try to send it like this
$http({
method: 'POST',
url: 'http://localhost:3000/api/evaluations',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: newEvaluation
}).success(function (data) {
console.log(data);
}).error(function(data){
console.log(data);
});
because your newEvaluation is already an object.
Your newEvaluation data is a string.
'{"evaluation":{"title":"Sports","description":"Just do it","notifFreq":"daily"}}': ''
Please send javascript object to backend. Split your string first by ":" character and then parse json string to json object.
$scope.addNewEvaluation = function (newEvaluation) {
var splitStr = newEvaluation.split(":")[0],
newEvaluationObj = JSON.parse(splitStr);
dataService.addNewEvaluation(splitStr);
$scope.closeModal();
};
I have a problem with angular $http get with Authorization header.
I tried to excute the same request with different rest client and response are the same each one.
Advanced Rest Client Chrome extension
Soap-Ui
Insomnia
I have always received the same response with 200 status code.
but when I try to make the same call from my angular application I get 403 status code and response is an OPTIONS.
where I'm wrong?
this is my code:
Config
app.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common['Authorization']='Bearer 24ac24e6-0f9b-48b5-923f-b75986226bd9';
});
Service
app.service('DiscoveryService', function ($http) {
this.getData = function (callbackFunc) {
$http({
url: 'https://test.test/test-api/source-monitor/v1/discover',
method: 'GET',
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
console.log(response);
}).error(function (error) {
console.log(response);
});
};
});
Controller
DiscoveryService.getData(function (dataResponse) {
$scope.data = dataResponse;
});
I want to get access token for authentication. My post result like
POST https://staj-io-goldenilkay92-1.c9.io/api/v1/oauth/token 401 (Unauthorized)
but when I try to post with postman it works.
Server Side Headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.header('Content-Type', 'application/json');
Angular Code
Service
function signIn(data) {
var deferred = $q.defer();
$http.post('https://staj-io-goldenilkay92-1.c9.io/api/v1/oauth/token', data,
{headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
)
.success(function (response, status, headers, config) {
deferred.resolve(response);
}).error(function () {
deferred.reject("Failed to login");
});
return deferred.promise;
}
controller
vm.loginData = {
'client_id': 'client',
'client_secret': 'client',
'grant_type': 'password',
'username': '',
'password': ''
};
vm.login = function login() {
loginService.signIn(vm.loginData).then(function (result) {
vm.signInResult = result;
},
function (data) {
});
}
POST https://staj-io-goldenilkay92-1.c9.io/api/v1/oauth/token 401 (Unauthorized)
Here is suggestions to solve your problem;
Use cors module (not required);
Server Side
I assume that your passport code working properly.
var cors= require('cors');
//init first.
app.options(cors({origin'*'})); //Use your origins.
app.use(cors({origin'*'})); //Use your origins.
Client Side
Just delete headers options
//...
$http.post('https://staj-io-goldenilkay92-1.c9.io/api/v1/oauth/token', data)
.success(function (response, status, headers, config) {
deferred.resolve(response);
}).error(function () {
deferred.reject("Failed to login");
});
//...
If one POST works and the other doesn't, then your angularjs $http request is making the request with the wrong parameters.
I'd suggest you to get an http analyser (like Fiddler) and compare the actual request done by Postman vs the request done by you angular app.
I am developing mobile application in cordova/phonegap. I am using angularJS for front-end. I am calling services which required 'API-KEY' attribute as header in post request.
I show some documentations, and tried with those way. but not worked.
postServiceDataWithHeader: function (url, data) {
var deferred = $q.defer();
var req = {
method: 'POST',
url: url,
data: JSON.stringify(data),
headers: {
'user-Token': $rootScope.user.APIKEY,
'content-Type': 'Application/Json'
}
}
$http(req).success(function (data) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
alert("Server failed to save data");
deferred.reject(status);
});
return deferred.promise;
}
I tried to add headers in call with,
JodoModule.config(function ($routeProvider, $httpProvider) {
$httpProvider.defaults.headers.post['user-Token'] = 'finding???';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
});
and second approach was,
JodoModule.run(['$rootScope', '$http', function ($rootScope, $http) {
$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
}]);
I am able to call services, but on server side, I am not getting header values, even in fiddler also headers are not passed.
What is the reason ? Do I need to add anything else in code for passing headers for each POST request. ?
I've made working plunker for you using one of yours approach
http://plnkr.co/edit/36Dq6UXgyeMEXOzycrua?p=preview
app.config(function ( $httpProvider) {
$httpProvider.defaults.headers.post['User-Token'] = 'finding???';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
});
Although if it's CORS you have to add 'User-Token' to accepted headers
i.e. for apache2
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "origin, user-token, x-requested-with, content-type"
Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"