$resource POST Error 400 - angularjs
Hi guys i'm working with angular $resource to make POST call. This is my FE function
$scope.showPrompt = function (ev) {
$scope.usernameSelected = [];
$scope.users.forEach(function (element) {
if (element.checked)
$scope.usernameSelected.push(element);
console.log($scope.usernameSelected);
});
var conferma = $mdDialog.prompt()
.title('Insert group name?')
.clickOutsideToClose(true)
//.textContent('Bowser is a common name.')
.placeholder('Group name')
.ariaLabel('Group name')
.targetEvent(ev)
.ok('Crea gruppo')
.cancel('Annulla');
$mdDialog.show(conferma).then(function (result) {
GroupService.group({}, {
creatore: $cookieStore.get('username'),
gruppo: result,
partecipanti: $scope.usernameSelected},
function (data) {
console.log("GRUPPO", data);
});
$scope.status = 'NOMEGRUPPO: ' + result + '.'; //inserito il nome gruppo
}, function () {
$scope.status = 'INSERT NOME GRUPPO';
});
};
This the GroupService:
var groupService = angular.module("groupService",['ngResource']);
groupService.factory("GroupService",['$resource',
function($resource){
var url = "";
return $resource("",{},{
group: {method : "POST", url:url+"group", isArray: false},
findGroup: {method : "GET", url:url+"findGroup", isArray: true}
});
}]);
I have this error:
angular.js:14328 Possibly unhandled rejection: {"data":"<!DOCTYPE html><html><head><title>Apache Tomcat/8.5.11 - Error report</title><style type=\"text/css\">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style> </head><body><h1>HTTP Status 400 - </h1><div class=\"line\"></div><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The request sent by the client was syntactically incorrect.</u></p><hr class=\"line\"><h3>Apache Tomcat/8.5.11</h3></body></html>","status":400,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"group","data":{"creatore":"ciro","gruppo":"nuovo","partecipanti":[{"id":0,"username":"a","email":"a#aa","password":null,"name":"a","surname":"a","longitude":0,"latitude":0,"checked":true},{"id":0,"username":"ciao","email":"ciao#ciao","password":null,"name":"ciao","surname":"ciao","longitude":0,"latitude":0,"checked":true}]},"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":""}
This is my BE code. I have a spring controller that manage client requests
#RequestMapping(value = "/group", method = RequestMethod.POST)
public #ResponseBody
Group createGroup(#RequestBody Group json, HttpServletRequest request) throws SQLException, ClassNotFoundException {
Group g = DBUtils.insertGroup(json.getPartecipanti(), json.getGruppo(), json.getCreatore());
return g;
}
This is my DBUtils.insertGroup
public static Group insertGroup(List<String> members, String groupName, String userCreator) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn;
conn = DriverManager.getConnection(DB_URL, USER, PASS);
String sql = "insert into gruppo \n"
+ " (idCreatorUser,groupName,idPartecipante,data) values (?,?,?,?) ";
PreparedStatement pstm = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
java.util.Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
Utente creator = DBUtils.findUser(userCreator);
pstm.setInt(1, creator.getId());
pstm.setString(2, groupName);
pstm.setInt(3, creator.getId());
pstm.setTimestamp(4, timestamp);
int res = pstm.executeUpdate();
ResultSet rsId = pstm.getGeneratedKeys();
rsId.next();
int idGruppo = rsId.getInt(1);
Group response = new Group();
response.setIdGruppo(idGruppo);
response.setGruppo(groupName);
response.setIdCreatore(creator.getId());
response.setData(timestamp);
response.setPartecipanti(members);
response.setCreatore(creator.getUsername());
System.out.println(response);
sql = "insert ignore into gruppo \n"
+ " (idGruppo,idCreatorUser,groupName,idPartecipante,data) values (?,?,?,?,?) ";
pstm = conn.prepareStatement(sql);
Utente part;
for (int i = 0; i < members.size(); i++) {
pstm.setInt(1, idGruppo);
pstm.setInt(2, creator.getId());
pstm.setString(3, groupName);
part = DBUtils.findUser(members.get(i));
pstm.setInt(4, part.getId());
pstm.setTimestamp(5, timestamp);
pstm.executeUpdate();
}
conn.close();
return response;
}
I want to send in body some parameters but I can't to figure out what is the syntact error made.
Related
Gatling scala - Unable to replace session variable in the request URI
I do have a session variable named AuctionId and couldn't replace AuctionId here in the POST request URI. Can you please advise what I am missing here? object BidSubmission extends HttpUtil { val orders_feeder = csv("data/Round-1.csv").circular def orderSubmission: ChainBuilder = pause(pauseBy(5) seconds) .repeat(1) { feed(orders_feeder) .exec(postToUri("${Constants.orderSubmission_URL}/#{AuctionId}/base-orders/proxy-bid", "") .queryParam("employeeId", "#{empNo}") .body(StringBody(session => { println(session) println(session.attributes("empNo")) val empNo = session.attributes("empNo").asInstanceOf[String] val orderNo = session.attributes("orderNo").asInstanceOf[String] println(s"\n\n\n $orderNo \n\n\n") println("\n\n\n ${Constants.bidSubmission_URL}/#{AuctionId}/base-auctions/proxy- bid \n\n\n") var slotNos = orderNo.replace("[", "").replace("]", "").split(" +") println(s"\n\n\n ${generatePayload(empNo, slotNos)} \n\n\n") generatePayload(empNo, slotNos) " " })) ) } it prints uri like this instead of replacing AuctionId with the session variable value- https://order.com/golden/base-auction/system-override/auctions/#{AuctionId}/base-auctions/proxy-bid trait HttpUtil extends StrictLogging { def postToUri(uri: String, requestName: String, statusCode: Int = 201): HttpRequestBuilder = { appendHeaders(http(requestName).post(uri)).check(status.is(statusCode)) } private def appendHeaders(request: HttpRequestBuilder, authScheme: String = config.auth.plannerToken): HttpRequestBuilder = { request .header("Authorization", authScheme) .header("Content-Type", "application/json") .header("Accept", "application/prs.hal-forms+json") } }
Selects from multiple tables for Activities feed
I have a social app for which I am trying to create a friend activities feed using Azure Sql Server. I have 3 tables I want to select from: Songs -createdAt -id -userId -trackName -etc Comments -createdAt -id -userId -songId -text Likes -createdAt -id -userId -songId I have the users that the current user is following stored in an array named 'follows'. How do I go about selecting the 40 most recent items from those 3 tables where userId in each table is in the follows array? Edit: function getActivities(userId) { var deferred = Q.defer(); var follows = []; getFollowing(userId).then(function (results) { follows.push(userId); _.each(results, function (user) { follows.push(user.toUserId); }); return; }).then(function () { var stringified = "'" + follows.join("','") + "'"; var queryString = "SELECT * FROM comments, songs, likes WHERE comments.userId IN (" + stringified + ") OR songs.userId IN (" + stringified +") OR likes.userId IN (" + stringified + ")"; var params = []; return sqlQuery(queryString, params); }).then(function (results) { console.log('Activities: ', results); deferred.resolve(results); }, function (error) { console.log('Error: ', error.message); deferred.reject(error.message); }); return deferred.promise; }
Alright, so I dug into JOINS a little more and realized how easy it actually is once you wrap your head around it. Here is what I did to complete this: var queryString = "SELECT TOP 50 follows.id AS followId, follows.toUserId AS followToUserId, follows.fromUserId AS followFromUserId, comments.text AS commentText, profiles.userId, profiles.username, profiles.name, profiles.profileImage, songs.trackId, songs.trackName, songs.artistName, songs.collectionName, songs.artworkUrl100, songs.caption, songs.id AS songId, activities.id AS activityId, activities.type AS activityType, activities.objectId AS activityObjectId, activities.parentType AS activityParentType, activities.parentId AS activityParentId, activities.__createdAt AS activityCreatedAt FROM activities "; queryString += "INNER JOIN profiles ON (profiles.userId = activities.userId) "; queryString += "LEFT JOIN songs ON (songs.id = activities.objectId AND activities.type = 'songs') OR (songs.id = activities.parentId AND activities.parentType = 'songs') "; queryString += "LEFT JOIN comments ON (activities.type = 'comments' AND comments.id = activities.objectId) "; queryString += "LEFT JOIN follows ON (activities.type = 'followed' AND activities.userid = follows.fromUserId) "; queryString += "WHERE activities.userId IN (SELECT follows.toUserId AS userId FROM follows WHERE follows.fromUserId = ? AND follows.isFollowed = 'true') "; queryString += "ORDER BY activities.__createdAt DESC"; var params = [userId]; mssql.query(queryString, params, { success: function (results) { _.each(results, function (result) { //Remove columns with null or undefined values for (var i in result) { if (result[i] === null || result[i] === undefined) { delete result[i]; } } }); response.send(200, results); }, error: function (error) { response.send(400, error.message); } });
Facing trouble while inserting bulk data into sql
In MVC4 , i have following code in my view : <script> var things = []; function fun () { var Quran = { "surah": things[1].surah, "ayah": things[1].ayah, "verse": things[1].verse }; things.push(Quran); for (var n = 0; n < length; n++) { $.ajax({ contentType: 'application/json; charset=utf-8', method: 'GET', url: "Gateway/DB_Rola?action=1", data: things[n], success: function (Data) { var mera_obj = Data.key; document.getElementById("Param2").value = '(' + mera_obj.Response_Code + ' , ' + mera_obj.Response_Description + ')'; }, error: function () { alert("ERROR: can't connect to Server this time"); return false; } }); alert("done for "+(n+1)); } // loop ends return false; }; // function ends and controller method is : public ActionResult DB_Rola(thing things) { string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\PROGRAM FILES (X86)\MICROSOFT SQL SERVER\MSSQL.1\MSSQL\DATA\PEACE_QURAN.MDF;Integrated Security=True"; System.Data.SqlClient.SqlConnection connection = new SqlConnection(connectionString); int surah = things.surah; int ayah =things.ayah; String verse = things.verse; // designing parametiric_query from the parameters string query = "insert into Ayyat_Translation_Language_old_20131209 values(null,null,#Surah,#Verse)"; SqlCommand cmd = new SqlCommand(query, connection); connection.Open(); //setting parameters for parametric query SqlParameter Parm1 = new SqlParameter("Surah", surah); SqlParameter Parm2 = new SqlParameter("Ayah", ayah); SqlParameter Parm3 = new SqlParameter("Verse", verse); //adding parameters cmd.Parameters.Add(Parm1); cmd.Parameters.Add(Parm2); cmd.Parameters.Add(Parm3); cmd.ExecuteNonQuery(); System.IO.StreamWriter file = new System.IO.StreamWriter(#"E:\Office_Work\Peace_Quran\Peace_Quran\Files\hisaab.txt", true); file.WriteLine(" "+things.ayah); file.Close(); connection.Close(); return View(); } as mentioned above in code ,there is loop in my view page that passes single object at a time which is received in above controller method .it works for small amount of data but when i send bulk .i.e. 50+ records at once, some of records are not saved in my DB. i don't know what's wrong with my DB code. please help me figure it out.
Couldn't send and store String data to database through WCF
I have created a Windows 8 app, I have a table in SQL server database to store people's name, " [Name] VARCHAR (50)" I have manage to send and save integer values to database, but when i modified my coding to store the string, it does not work, table data is empty. Please help! itemDetail.html <div> <input id="join1" type="text" /> <button id="joinbtn">insert</button> </div> itemDetail.js var joinButton = document.getElementById('joinbtn'); // Register Click event joinButton.addEventListener("click", joinButtonClick, false); function joinButtonClick() { // Retrieve element var baseURI2 = "http://localhost:45573/AddService.svc/Join"; var jointext = document.getElementById('join1').value; WinJS.xhr({ type: "POST", url: baseURI2, headers: { "Content-type": "application/json" }, data: '{"namet":' + jointext + '}' }).then(function complete(request) { var resdata = request.responseText; }, function error(er) { var err = er.statusText; }) } AddService.svc.cs public void Join(string namet) { string connectionString = System.Configuration.ConfigurationManager. ConnectionStrings["Database1ConnectionString1"].ConnectionString; SqlConnection con = new SqlConnection(connectionString); string sql = "INSERT INTO Table2(Name) VALUES (#Name)"; SqlCommand cmd = new SqlCommand(sql, con); cmd.Parameters.AddWithValue("#Name", namet); try { con.Open(); int numAff = cmd.ExecuteNonQuery(); } con.Close(); } IAddService.cs [OperationContract] [WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)] void Join(string namet); Thank you!
I think the problem may be in this line data: '{"namet":' + jointext + '}' Try changing it to data: '{"namet":\'' + jointext + '\'}'
Post data to web API
I've been trying to send data to a web API VIA post. But it doesn't seem to be sending it. Here's how I do it. var baseAddress = "http://192.168.0.103/vchatapi/api/Images?gsmNumber=" + profileNumberLbl.Content + "&content=" + base64 + "&contentType=image/" + contentType; var http = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new System.Uri(baseAddress)); http.Accept = "application/json"; http.ContentType = "application/json"; http.Method = "POST"; This code works with get: var baseAddress = "http://192.168.0.103/vchatapi/api/SendSMSVerificationCode?gsmNumber=" + areCode + mobile + "&udid=123456"; var http = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new System.Uri(baseAddress)); http.Accept = "application/json"; http.ContentType = "application/json"; http.Method = "GET"; try { var response = http.GetResponse(); var stream = response.GetResponseStream(); var sr = new StreamReader(stream); var content = sr.ReadToEnd(); verificationCode = verificationCode.FromJson(content); if (!verificationCode.Equals("")) { MessageBox.Show(this, "Verification Code: " + verificationCode); verificationTextBox.IsEnabled = true; areaCodeCB.IsEnabled = false; mobileNumberTB.IsEnabled = false; } else { MessageBox.Show(this, "Invalid Number"); } } catch (Exception ex) { MessageBox.Show(this, ex.Message); } Any ideas? Thanks!
Since you are doing a POST, you would be sending the content in the body of the request. You would need to get hold of the request's stream and write data to it. The following answer post has a very concise example: https://stackoverflow.com/a/2551006/1184056