I am trying to add a new Stop to my database. But I get a 401 error in asp.net.
.js file:
(function () {
"use strict";
angular.module("app-trips")
.controller("tripEditorController", tripEditorController);
function tripEditorController($routeParams, $http) {
var vm = this;
vm.tripName = $routeParams.tripName;
vm.stops = [];
vm.newStop = {};
vm.addStop = function () {
alert(vm.newStop.name);
$http.post("/api/trips/" + vm.tripName + "/stops", vm.newStop)
.then(function (response) {
vm.stops.push(vm.newStop);
};
}
}
.html file (input form):
<form novalidate name="newStopForm" ng-submit="vm.addStop()">
<div class="form-group">
<label for="">Date</label>
<input class="form-control" id="arrival" name="arrival" ng-model="vm.newStop.arrival" required />
</div>
<div class="form-group">
<label>Location</label>
<input class="form-control" id="name" name="name" ng-model="vm.newStop.name" required ng-minlength="3" />
</div>
<div>
<input type="submit" value="Add" class="btn btn-success" ng-disabled="newStopForm.$invalid" />
</div>
</form>
C# Post code:
[HttpPost("/api/trips/{tripName}/stops")]
public async Task<IActionResult> Post(string tripName, [FromBody]StopViewModel vm)
{
try
{
if (ModelState.IsValid)
{
var newStop = Mapper.Map<Stop>(vm);
var result =await _coordsService.GetCoordsAsync(newStop.Name);
if (!result.Succes)
{
_logger.LogError(result.Message);
}
else
{
newStop.Latitude = result.Latitude;
newStop.Longitude = result.Longitude;
}
_repository.AddStop(tripName, newStop, User.Identity.Name);
if (await _repository.SaveChangesAsync())
{
return Created($"/api/trips/{tripName}/stops/{newStop.Name}",
Mapper.Map<StopViewModel>(newStop));
}
}
}
catch (Exception ex)
{
_logger.LogError("Failed to save new Stop: {0}", ex);
}
return BadRequest("Failed to save new stop");
}
GeoCoordsService.cs:
public async Task<GeoCoordsResult> GetCoordsAsync(string name)
{
var result = new GeoCoordsResult()
{
Succes = false,
Message = "Failed to get coordinates"
};
var apiKey = _config["Keys:BingKey"];
var encodedName = WebUtility.UrlEncode(name);
var url = $"http://dev.virtualearth.net/REST/v1/Locations?q={encodedName}&key={apiKey}";
var client = new HttpClient();
var json = await client.GetStringAsync(url);
var results = JObject.Parse(json);
var resources = results["resourceSets"][0]["resources"];
if (!resources.HasValues)
{
result.Message = $"Could not find '{name}' as a location";
}
else
{
var confidence = (string)resources[0]["confidence"];
if (confidence != "High")
{
result.Message = $"Could not find a confident match for '{name}' as a location";
}
else
{
var coords = resources[0]["geocodePoints"][0]["coordinates"];
result.Latitude = (double)coords[0];
result.Longitude = (double)coords[1];
result.Succes = true;
result.Message = "Success";
}
}
return result;
}
I have read, that this is probably caused because the data is not in the right format, does anyone know what would be the right format, my webpage returns error 400, but deeper in my C# I can see that function var json = await client.GetStringAsync(url);is returning an error 401 (Unotharized). I guess I should also add username somewhere, but I don't know where.
You're getting a 400 because the request you sent isn't what the server is expecting. Find out the object the server is expecting on that endpoint. Then form your request body to match that object.
Related
Issue: An object created in JavaScript by input data from a signup form in HTML does not seem to be created.
Tried:
I checked if I was referencing the entire object with {data} rather just data
Searched other online resources to no avail
Read again on JavaScript objects to see if I did a simple mistake
adding debug strings to give me hints (I will list code below)
Relevant Code:
signup.html(each snippet is in top to bottom order):
<form id="signup-form" name ="signup-form">
<input class="login-form-field" type="text" name="user" placeholder="username">
<input class="login-form-field" type="text" name="email" placeholder="email">
<input class="login-form-field" type="password" name="dob" placeholder="date of birth">
<br>
<!--<button class="actionButton"></button>-->
<INPUT TYPE="button" NAME="button" Value="Click" onClick="signupData(this.form)">
</form>
//last of the markup body with Browserify compiled JavaScript files linked for functionality
<script src="browserify/builds/genKey.js"></script>
<script src="browserify/builds/SignUp.js"></script>
<script LANGUAGE="JavaScript">
function signupData(form) // add to this script
{
console.log("signup data is starting");
var user = form.user.value;
var email = form.email.value;
var dob = form.dob.value;
genSKey();
genPKey();
var skey = getSKey();
// var enUser = encryptMes(user);
// var enEmail = encryptMes(email);
var endob = encryptMes(dob);
var data = { name: "LifeNet", members: { user: {profilePic: {}, endob, listeners: {}, listening: {}, friends: {}, requested: {}, blocked:{}, channel: false} } }
apiPost({data});
// pass the signup function in here
// hash the variables and send to celox network
console.log(JSON.stringify({data}));
alert (`copy and save your Private Key to somewhere safe: ${skey}`);
}
</script>
signup.js (pre-Browserify build):
window.apiPost = function({data})
{
fetch("https://goldengates.club:3000/api/passData",
{
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({data})
}
);
}
build.js (pre-Browserify build):
var eccrypto = require("eccrypto");
window.genSKey = function()
{
var secretKey = eccrypto.generatePrivate();
var SKey = JSON.stringify(secretKey);
localStorage.setItem("skey", SKey);
console.log(SKey);
alert(`your private key is ${SKey}`)
}
window.genPKey = function()
{
var skey = localStorage.getItem("skey");
var SKey = JSON.parse(skey);
let publicKey;
if(SKey != null)
{
publicKey = eccrypto.getPublic(SKey);
localStorage.setItem("pkey", JSON.stringify(publicKey));
return;
}
publicKey = eccrypto.getPublic(privateKey);
localStorage.setItem("pkey", JSON.stringify(publicKey));
return;
}
window.getPKey = function()
{
var PKey = localStorage.getItem("pkey");
var pkey = JSON.parse(PKey);
return pkey;
}
window.getSKey = function()
{
var SKey = localStorage.getItem("skey");
var skey = JSON.parse(SKey);
return skey;
}
window.encryptMes = function(data)
{
//for this you need to get the sender's public key to encrypt the message
if (localStorage.getItem("pkey") === null)
{
if (localStorage.getItem("skey") === null)
{
genSKey();
genPKey();
}
}
var pkey = getPKey();
encryptedMes = eccrypto.encrypt(pkey, Buffer.from(data));
return encryptedMes;
}
window.decryptMes = function(data)
{
if (localStorage.getItem("skey") === null)
{
genSKey();
}
var skey = getSKey();
decryptedMes = eccrypto.decrypt(SKey, data);
return decryptedMes.toString();
}
window.encryptData = function()
{
genSKey();
genPKey();
enMes = encryptedMes(/*add a document search for all fields on input form in login*/);
}
window.decryptData = function() {}
Error Code:
Browser:
It runs everything in the signup.html file besides console.log(JSON.stringify({data})); in the signupData(form) function.
Suspicious since the object that was created with user data should have been created and printed to the console.
My API Console:
I won't reference the API code since it seems to me that the object is just not being posted to it and that it isn't the problem.
TypeError: Cannot read property 'name' of undefined
at dataPool.setData (/home/main/public_html/Cypher-Network/src/app/data-Pool.js:64:27)
at /home/main/public_html/Cypher-Network/src/index.js:198:12
at Layer.handle [as handle_request] (/home/main/public_html/Cypher-Network/node_modules/express/lib/router/layer.js:95:5)
at next (/home/main/public_html/Cypher-Network/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/main/public_html/Cypher-Network/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/main/public_html/Cypher-Network/node_modules/express/lib/router/layer.js:95:5)
at /home/main/public_html/Cypher-Network/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/main/public_html/Cypher-Network/node_modules/express/lib/router/index.js:335:12)
at next (/home/main/public_html/Cypher-Network/node_modules/express/lib/router/index.js:275:10)
at /home/main/public_html/Cypher-Network/src/index.js:62:3
Any form of help and explanation is greatly appreciated, as I am pretty new to the way JavaScript works.
Are you making use of NodeJs, and a framework like express? If yes, then you have to be sure that your backend is able to pass the incoming JSON request. If you use express, you can just use the express.json() middleware. Make sure you put it at the top of other middleware or just after the cors middleware like so
app.use(express.json())
That will parse the incoming data from the frontend.
Good afternoon, I'm writing chat in Perl using Mysql and the Websocket protocol.
I am using the AnyEvent module and Protocol :: WebSocket.
I understand that it would be better to use Mojo or Node.js for this, but in my case it needs to be that way.
I receive data from Websocket, reverse and connect. The data entered in the input field also fits into the database.
My problem is that how can I now output this data to the web interface in real time.
#!/usr/bin/env perl
use strict;
use warnings;
use AnyEvent;
use AnyEvent::Handle;
use AnyEvent::DBI::MySQL;
use AnyEvent::Socket;
use Protocol::WebSocket::Handshake::Server;
use Protocol::WebSocket::Frame;
my $dbh = AnyEvent::DBI::MySQL->connect("DBI:mysql:chat:localhost", "admin", "admin",
{
mysql_enable_utf8 => 1,
PrintError => 0,
}) or die;
my $cv = AnyEvent->condvar;
my $hdl;
my $sth;
AnyEvent::Socket::tcp_server undef, 3000, sub {
my ($clsock, $host, $port) = #_;
my $hs = Protocol::WebSocket::Handshake::Server->new;
my $frame = Protocol::WebSocket::Frame->new;
$hdl = AnyEvent::Handle->new(fh => $clsock);
$hdl->on_read(
sub {
my $hdl = shift;
my $chunk = $hdl->{rbuf};
$hdl->{rbuf} = undef;
if (!$hs->is_done) {
$hs->parse($chunk);
if ($hs->is_done) {
$hdl->push_write($hs->to_string);
return;
}
}
$frame->append($chunk);
my $message = $frame->next;
if ($message eq ""){
$message = undef;
} else {
$sth = $dbh->do("INSERT INTO web_chat VALUES('$message')", { async => 0 });
}
my $ary_ref = $dbh->selectcol_arrayref("SELECT text FROM web_chat");
}
);
};
$cv->wait;
1;
Client is not written in Javascript
<!doctype html>
<form name="publish">
<input type="text" name="message" maxlength="50"/>
<input type="submit" value="Send"/>
</form>
<div id="messages"></div>
<script>
let socket = new WebSocket('ws://192.168.1.1:3000/websocket/');
// отправка сообщения из формы
document.forms.publish.onsubmit = function() {
let outgoingMessage = this.message.value;
socket.send(outgoingMessage);
return false;
};
socket.onopen = function () {
console.log("Websocket Connection");
};
socket.onerror = function () {
console.log("Error websocket connection ");
}
// прослушка входящих сообщений
socket.onmessage = function(event) {
let incomingMessage = event.data;
showMessage(incomingMessage);
};
socket.onclose = event => console.log(`Closed ${event.code}`);
// отображение информации в div#messages
function showMessage(message) {
let messageElem = document.createElement('div');
messageElem.textContent = message;
document.getElementById('messages').prepend(messageElem);
}
</script>
May I suggest Mojolicious and Mojo::Mysql for this?
Protocol::WebSocket is pretty “bare-bones” and doesn’t handle a lot of the protocol details like ping/pong.
I used to host a website at carrd.co with the pro plus plan. I chose the expensive plan because of the possibility to download the website and host it on an own server.
What I did not know, was that this did not include server-side code.
My problem is, that I have the front end code, but every PHP code I try fails to interact with this code. Since I can only develop with Java, I cannot get to a solution by myself.
The issue is that I do not know what the next step is to make this code work on my server so that it successfully sends me an email when this form is submitted by a user. I do not have any backend code and do not know where to start.
1) where can i put a PHP file to answer to this request? How do i have to name it?
2) how can i parse the arguments?
3) how do i have to format the answer from the php script to the ajax script?
Could you guys please help here? Thanks a lot!!!
(i might even be able to solve this with some good hints if you cannot be bothered to provide a full solution! I'm thankful for any advice!)
The frontend code:
Form:
<form id="form02" method="post">
<div class="inner">
<div class="field"><input type="text" name="name" id="name" placeholder="Name"
maxlength="128"/></div>
<div class="field"><input type="email" name="email" id="email"
placeholder="Email" maxlength="128"/></div>
<div class="field"><input type="text" name="fname" id="-fname" placeholder="Fname"
maxlength="128"/></div>
<div class="field"><textarea name="message" id="message" placeholder="Message"
maxlength="16384"></textarea></div>
<div class="actions">
<button type="submit">Send Message</button>
</div>
</div>
<input type="hidden" name="id" value="form02"/>
</form>
Script:
function form(id, settings) {
var _this = this;
this.id = id;
this.mode = settings.mode;
this.method = settings.method;
this.success = settings.success;
this.preHandler = ('preHandler' in settings ? settings.preHandler : null);
this.failure = ('failure' in settings ? settings.failure : null);
this.optional = ('optional' in settings ? settings.optional : []);
this.$form = $('#' + this.id);
this.$form.addEventListener('submit', function (event) {
_this.submit(event);
});
this.$form.addEventListener('keydown', function (event) {
if (event.keyCode == 13 && event.ctrlKey) {
event.preventDefault();
event.stopPropagation();
_this.submit(event);
}
});
var x = $('#' + this.id + ' input[name="' + settings.hid + '"]');
if (x) {
x.disabled = true;
x.parentNode.style.display = 'none';
}
this.$submit = $('#' + this.id + ' button[type="submit"]');
this.$submit.disabled = false;
};form.prototype.notify = function (type, message) {
if (message.match(/^(#[a-zA-Z0-9\_\-]+|[a-z0-9\-\.]+:[a-zA-Z0- 9\~\!\#\#$\%\&\-\_\+\=\;\,\.\?\/\:]+)$/)) location.href = message; else alert((type == 'failure' ? 'Error: ' : '') + message);
};
form.prototype.submit = function (event) {
var _this = this, result, handler, fd, k, x, $f, $ff;
event.preventDefault();
if (this.$submit.disabled) return;
result = true;
$ff = this.$form.elements;
for (k in $ff) {
$f = $ff[k];
if ($f.type != 'text' && $f.type != 'email' && $f.type != 'textarea' && $f.type != 'select-one') continue;
if ($f.disabled) continue;
if ($f.value === '' || $f.value === null) {
if (this.optional.indexOf($f.name) !== -1) continue;
result = false;
} else {
x = '';
switch ($f.type) {
case 'email':
x = "^([a-zA-Z0-9\\_\\-\\.\\+]+)#([a-zA-Z0-9\\- \\.]+)\\.([a-zA-Z]+)$";
break;
case 'select':
x = "^[a-zA-Z0-9\\-]$";
break;
default:
case 'text':
case 'textarea':
x = "^[^\\<\\>]+$";
break;
}
result = result && $f.value.match(new RegExp(x));
}
if (!result) break;
}
if (!result) {
this.notify('failure', 'Missing and/or invalid fields. Please try again.');
return;
}
if (_this.method == 'get') {
_this.$form.submit();
return;
}
if (x = $(':focus')) x.blur();
this.$submit.disabled = true;
this.$submit.classList.add('waiting');
handler = function (values) {
var x, k, data;
data = new FormData(_this.$form);
if (values) for (k in values) data.append(k, values[k]);
x = new XMLHttpRequest();
x.open('POST', ['', 'post', _this.mode].join('/'));
x.send(data);
x.onreadystatechange = function () {
var result = false, message = 'Sorry, something went wrong. Please try again later.', alert = true, o;
if (x.readyState != 4) return;
if (x.status == 200) {
o = JSON.parse(x.responseText);
if (o) {
if ('result' in o) result = (o.result === true);
if (('message' in o) && o.message) message = o.message;
if ('alert' in o) alert = (o.alert === true);
}
}
_this.$submit.classList.remove('waiting');
if (result) {
_this.$form.reset();
if (alert) window.alert(message); else _this.notify('success', (_this.success ? _this.success : message));
} else {
if (alert) window.alert(message); else _this.notify('failure', (_this.failure ? _this.failure : message));
}
_this.$submit.disabled = false;
};
};
if (_this.preHandler) (_this.preHandler)(_this, handler); else (handler)();
};
new form('form02', {mode: 'contact', method: 'post', hid: 'fname', success: '#contact-done',});
An html form normally uses an action parameter to specify a url for the script to submit the form data to. However it looks like your javascript code is hard-coded to create an ajax post back to a url at /post/contact, which may explain why the examples you have tried do not work.
Yes, you do need a script of some kind on your server to process the response, but it doesn't have to be PHP - whatever your hosting provider supports, and whatever is capable of handling what you want to do with the data.
Here i am getting my Error Messages from a separate page and i am displaying it in a a div called #stage_error
$('#stage_error').html(error_string);
So, the errors will be displayed like this
The bus no field is required.
The comp id field is required.
The total seats field is required.
But what i want is to display the errors in its respective div's
i.e., the Bus no should be displayed near the div <div id='busno'> like this.
How can i do that ?
Json :
{"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}
Update :
Script for request and showing error :
<script>
$(document).ready(function() {
$("#driver").click(function(event) {
var BusNo = $("#BusNo").val();
var CompID = $("#CompID").val();
var TotalSeats = $("#TotalSeats").val();
var _token = $("#_token").val();
$.post("managebus_register", {
_token: _token,
BusNo: BusNo,
CompID: CompID,
TotalSeats: TotalSeats
},
function(data) {
if (data != '') {
obj = JSON.parse(data);
var error_string = '';
$.each(obj, function(entry) {
error_string += obj[entry] + '<br/>';
});
$('#stage_error').html(error_string);
} else {
$('#stage_success').text('Resistered Succesfully');
$("#stage_error").hide();
}
});
});
});
</script>
Laravel Controller :
public function managebusregister()
{
$BusNo = Input::get('BusNo');
$CompID = Input::get('CompID');
$TotalSeats = Input::get('TotalSeats');
$data = Input::except(array('_token')) ;
$rule = array(
'BusNo' => 'required|unique:company_bus',
'CompID' => 'required',
'TotalSeats' => 'required|max:50'
) ;
$validator = Validator::make($data,$rule);
if ($validator->fails())
{
$messages = $validator->messages();
return json_encode($validator->messages()); //php encoded value
}
else
{
DB::insert('insert into company_bus (BusNo, CompID, TotalSeats) values (?, ?, ?)',
array($BusNo, $CompID, $TotalSeats));
return '';
}
}
Html Code :
<div id="stage_error" style="color:red;font-size:15px"></div>
<div id="stage_success" style="color:green;font-size:20px"></div>
and beyond that i have each field input boxes,
<input type="text" id="BusNo" name="BusNo"/>
<input type="text" id="CompID" name="CompID"/>
How can i throw error messages near the respective fields
Below is the approach: Observe I've added spans with error after text boxes.
CSS
<style>
.error { color:red; font-size:15px; }
</style>
Html
<input type="text" id="BusNo" name="BusNo" /><span class="error"></span>
<input type="text" id="CompID" name="CompID" /><span class="error"></span>
JavaScript I did some changes as per the jQuery standard, it should work well, if you're not interested then you can ignore all the changes but can take only below mentioned if logic block.
The error display added in if (!data) {...}
$(function () {
$(document).on("click", "#driver", function (event) {
var BusNo = $("#BusNo").val(),
CompID = $("#CompID").val(),
TotalSeats = $("#TotalSeats").val(),
_token = $("#_token").val();
$.post("managebus_register", {
_token: _token,
BusNo: BusNo,
CompID: CompID,
TotalSeats: TotalSeats
}).done(function (data) {
$("span.error").empty();//All previous error messages cleared here.
if (!data) {
var obj = JSON.parse(data);
//obj = {"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}
$.each(obj, function (entry) {
var targetSelector='';
if (entry == "busno") {
targetSelector = "#BusNo";
}
if (entry == "Comp Id") {
targetSelector = "#CompID";
}
if(targetSelector) //Here we're setting error message for respective field
$(targetSelector).next("span.error").html(obj[entry]);
});
} else {
$('#stage_success').text('Resistered Succesfully');
$("#stage_error").hide();
}
});
});
});
you can try like this:
var json = JSON.parse('{"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}');
// alert(json['busno']);
$("#busno").html(json.busno);// like this for others also.
change here:
obj = JSON.parse(data);
var error_string = '';
$.each(obj, function(entry) {
error_string += obj[entry] + '<br/>';
if(entry == 'busno'){
$("#busno").html(obj[entry]);// like this for others also.
}
if(entry == 'Comp Id'){
$("#compid").html(obj[entry]);// like this for others also.
}
});
$('#stage_error').html(error_string);
I'm using the following code to get google contacts name and phone number. Authorization page itself is not coming properly it shows error as "The page you requested is invalid". :( pls help me to solve this...
`
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("gdata", "1.x");
var contactsService;
function setupContactsService()
{
contactsService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
}
function logMeIn() {
var scope = 'https://www.google.com/m8/feeds';
var token = google.accounts.user.login(scope);
}
function initFunc() {
setupContactsService();
logMeIn();
getMyContacts();
}
function checkLoggedIn(){
scope = "https://www.google.com/m8/feeds";
var token = google.accounts.user.checkLogin(scope);
if(token != "")
return true;
else
return false;
}
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full';
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
//We load all results by default//
query.setMaxResults(10);
contactsService.getContactFeed(query, handleContactsFeed, ContactsServiceInitError);
}
//Gets the contacts feed passed as parameter//
var handleContactsFeed = function(result) {
//All contact entries//
entries = result.feed.entry;
for (var i = 0; i < entries.length; i++) {
var contactEntry = entries[i];
var telNumbers = contactEntry.getPhoneNumbers();
var title = contactEntry.getTitle().getText();
}
}
</script>
<body>
<input type="submit" value="Login to Google" id="glogin" onclick="initFunc();">
</body>`
Thanks
It looks like you are trying to use the Google Contacts 1.X API. That's been deprecated. Look at the JavaScript examples for the Google 3.X API and see if that helps.
You can try this example
var config = {
'client_id': 'Client ID',
'scope': 'https://www.google.com/m8/feeds'
};
inviteContacts = function() {
gapi.auth.authorize($scope.config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.get("https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json", function(response) {
console.log(response);
//console.log(response.data.feed.entry);
});
}
Don't forget to add <script src="https://apis.google.com/js/client.js"></script> into your html file. Good Luck!