I'm trying to POST data to REST API but the server responds with an HTTP 405 error. I've tried many options like adding headers to the POST method, changing content type within the POST header but nothing seems to work out.
The exact response from the server is
{"detail":"Method \"POST\" not allowed."}.
HTML and JS code
<!DOCTYPE html>
<html>
<head>
<title>
New User Story
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('postserviceApp', []);
app.controller('postserviceCtrl', function ($scope, $http) {
$scope.jiraLink = null;
$scope.reporter = null;
$scope.assignee = null;
$scope.Reviewer = null;
$scope.summary = null;
$scope.description = null;
$scope.storyPoints = null;
$scope.postdata = function (jiralink, reporter, assignee, reviewer, summary, description, storypoints) {
var data = {
jiraLink: jiralink,
reporter: reporter,
assignee: assignee,
Reviewer: reviewer,
summary: summary,
description: description,
storyPoints: storypoints
};
//Call the services $http.post('/userStory/story', JSON.stringify(data))
$http({
method: 'POST',
url: '/userStory/story',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
data: data
}).then(function (response) {
if (response.data)
$scope.msg = "User story created Successfully!";
}, function (response) {
$scope.msg = "Couldn't create an User story";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
};
});
</script>
</head>
<body>
<div ng-app="postserviceApp" ng-controller="postserviceCtrl">
<div>
Jira Link : <input ng-model="jiralink" /><br/><br/>
Reporter : <input ng-model="reporter" /><br/><br/>
Assignee : <input ng-model="assignee" /><br/><br/>
Reviewer : <input ng-model="reviewer" /><br/><br/>
Summary : <input ng-model="summary" /><br/><br/>
Description : <input ng-model="description" /><br/><br/>
Story Points : <input ng-model="storypoints" /><br/><br/>
<input type="button" value="Create" ng-click="postdata(jiralink, reporter, assignee, reviewer, summary, description, storypoints)" /> <br/><br/>
</div>
<p>Output Message : {{msg}}</p>
<p>StatusCode: {{statusval}}</p>
<p>Status: {{statustext}}</p>
<p>Response Headers: {{headers}}</p>
</div>
</body>
</html>
models.py
from django.db import models
class Story(models.Model):
jiraLink = models.TextField(max_length=200)
reporter = models.TextField(max_length=50)
assignee = models.TextField(max_length=50)
Reviewer = models.TextField(max_length=50)
summary = models.TextField(max_length=50)
description = models.TextField(max_length=300, blank=True)
storyPoints = models.IntegerField(null=True, blank=True)
I'm not able to figure out where the problem. Any help is appriciated.
Related
Screenshot of UI
I'm having an issue invoking the inline javascript inside the mustache template file (.hjs).
when I click "Verify", the script tag and console logs do not run. It is not pulling the input code I type into the input box either.
For context: I am sending the mustache template (html) from my node server to an iFrame on the front end (React). I want the template to interact with the user and send an API call to my server and verify the 2FA.
I am sending variables to the javascript through {{ var }}, which is standard for mustache.
My thoughts: this code works in a regular index.html file.
any help or tips appreciated! I can try any suggestions locally to debug further.
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<body>
<div id="inline-widget" style="margin:0 auto;width: 360px;padding:5px">
<p style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Roboto','Oxygen','Ubuntu','Cantarell','Fira Sans','Droid Sans','Helvetica Neue',sans-serif;color:#48545d;font-size:14px;line-height:125%;margin:10px auto 20px;text-align:center">
Please complete your purchase by entering the 4 character code at the end of your recent charge description.
</p>
<img style="width: 350px;text-align:center;border:1px solid black" src="https://d2xxy1rwbjzckp.cloudfront.net/verification.jpeg" alt="Example"></img>
<p style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Roboto','Oxygen','Ubuntu','Cantarell','Fira Sans','Droid Sans','Helvetica Neue',sans-serif;color:#48545d;font-size:11px;line-height:125%;margin-bottom:10px auto 20px;text-align:left">
Code = 3122 in this example
</p>
<p id="error-message" style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Roboto','Oxygen','Ubuntu','Cantarell','Fira Sans','Droid Sans','Helvetica Neue',sans-serif;color:#48545d;font-size:11px;line-height:125%;margin-bottom:10px auto 20px;text-align:center;color:red"></p>
<div class="input-group mb-3">
<input id="2faCode" type="text" class="form-control" placeholder="4 digit code" aria-describedby="basic-addon2"/>
<div class="input-group-append">
<button class="btn btn-outline-secondary" id="verifyButton" type="button">Verify</button>
</div>
</div>
</div>
<script>
const button = document.getElementById('verifyButton');
button.addEventListener('click', async _ => {
try {
const verifyCode = document.getElementById('2faCode').value;
console.log('start!: ', verifyCode);
const response = await fetch({{ callbackUrl }}, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
orderId: {{ orderId }},
verificationCode: {{ verifyCode }}
})
});
const contentType = response.headers.get("content-type");
if (contentType === 'text/html; charset=utf-8') {
const textResponse = await response.text();
document.getElementById("inline-widget").innerHTML = textResponse;
} else {
const parsedResponse = await response.json();
document.getElementById("error-message").innerHTML = parsedResponse.message;
}
} catch(err) {
document.getElementById("error-message").innerHTML = err;
console.error(`Error: ${err}`);
}
});
</script>
</body>
</html>
Send Email Directly From JavaScript using EmailJS.
Please look the below answer and I'm getting so many comments for malicious attacks.. because this file is loading in browser so malicious user can easily get your key configuration. So, how to avoid it?
var templateParams = {
to_name: 'xyz',
from_name: 'abc',
message_html: 'Please Find out the attached file'
};
emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error);
});
Hi you can directly send email through using EmailJS without using the server side code. It'll totally client side.
For sending you need to configure below details.
1)First,Go to this site [https://www.emailjs.com/] and create free account.
2)below 'Connect your email service' button click and configure. You'll get 'YOUR_SERVICE_ID'
3)Then 'Create email template' button click and configure. You'll get 'YOUR_TEMPLATE_ID'
4)click on 'Send email from JavaScript' button. You'll get code.
5)You'll get the 'YOUR_USER_ID' in [https://dashboard.emailjs.com/account]
I did all configuration and added code please check. below code.
NOTE : - "Please encrypted or embedded your use_id for malicious attacks."
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2.4.0/dist/email.min.js">
</script>
<script type="text/javascript">
(function() {
emailjs.init("YOUR_USER_ID"); //please encrypted user id for malicious attacks
})();
//set the parameter as per you template parameter[https://dashboard.emailjs.com/templates]
var templateParams = {
to_name: 'xyz',
from_name: 'abc',
message_html: 'Please Find out the attached file'
};
emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error);
});
</script>
Using JavaScript can expose your credentials like user id , service id to the public. For this , you can store these keys values in a variable (half value) and then manipulating it in runtime like appending remaining half of the key etc. But its not totally safe.
Code :
<html>
<head>
<title>Contact Us</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2/dist/email.min.js"></script>
</head>
<body>
<div class="container">
<div class="card col-md-6 offset-md-3" style="margin-top:50px;">
<div class="card-body">
<h2>Contact Us</h2>
<label for="thename">Name</label>
<input type="text" class="form-control" id="thename" placeholder="Enter Name">
<label for="themail">Email:</label>
<input type="email" class="form-control" id="themail" placeholder="Enter Email">
<label for="themsg">Message</label>
<textarea class="form-control" id="themsg" placeholder="Enter Message"></textarea>
<button class="btn btn-danger btn-sm" style="margin-top:10px;" onCLick="sendemail();">Send</button>
</form>
</div>
</div>
</div>
<script>
function sendemail() {
var userid = "YourUserID"
emailjs.init(userid);
var thename = document.getElementById('thename').value;
var themail = document.getElementById('themail').value;
var themsg = document.getElementById('themsg').value;
var validmail = /^w+([.-]?w+)*#w+([.-]?w+)*(.w{2,3})+$/;
if (thename == "") {
alert("Please Enter Name");
}
else if (themail == "" || themail.match(!validmail)) {
alert("Please Enter Valid Email");
}
else if (themsg == "") {
alert("Please Enter Message");
}
else {
var contactdetail = {
from_name: thename,
from_email: themail,
message: themsg
};
emailjs.send('YourServiceID', 'YourTemplateID', contactdetail).then(function (res) {
alert("Email Sent Successfully");
},
reason => {
alert("Error Occur");
})
}
}
</script>
</body>
</html>
Make sure to replace "YourUserID" , "YourServiceID" & "YourTemplateID" with your own ids
Reference : Narendra Dwivedi - Send Email From JavaScript
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2.4.0/dist/email.min.js">
</script>
<script type="text/javascript">
(function() {
emailjs.init("service_ud48moz"); //please encrypted user id for malicious attacks
})();
//set the parameter as per you template parameter[https://dashboard.emailjs.com/templates]
var templateParams = {
to_name: 'xyz',
from_name: 'abc',
message_html: 'Please Find out the attached file'
};
emailjs.send('service_ud48moz', 'template_njhhxon', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error);
});
</script>
I want to display the list of record into webpage . I am using vuejs for front end development and mysql for backend .I created this applications by using LoopBack. I have some list of records inside the mysql database but the problem is when i run the web page , its does not display the records and when i want to insert new records , i am getting errors on this line ..
**(index):96 PUT http://localhost:3000/api/Account/ 400 (Bad Request)
storeAccount # (index):96
submit # VM346:3
invokeWithErrorHandling # vue.js:1863
invoker # vue.js:2188
original._wrapper # vue.js:7541**
When i clicked the index.js ,its showing error in this line
fetch(API, {...
Here is code for server.js file.
// Copyright IBM Corp. 2016. All Rights Reserved.
// Node module: loopback-workspace
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if `$ node server.js`
if (require.main === module)
app.start();
});
Here is my html code .
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="AccountApp">
<h1>Account List</h1>
<table>
<thead>
<tr>
<th>Id</th>
<th>Email Address</th>
<th>Created Date</th>
<th>Updated Date</th>
<td> </td>
</tr>
</thead>
<tbody>
<tr v-for="account in accounts">
<td #click="editAccount(account)" class="accountItem" title="Click to Edit">{{account.id}}</td>
<td>{{account.email}}</td>
<td>{{account.createdAt}}</td>
<td>{{account.lastModifiedAt}}</td>
<td #click="deleteAccount(account)" class="deleteAccount" title="Click to Delete">Delete</td>
</tr>
</tbody>
</table>
<form #submit.prevent="storeAccount">
<p>
<label for="email">Email</label>
<input type="text" id="email" v-model="account.email">
</p>
<p>
<label for="createdAt">Created At</label>
<input type="text" id="createdAt" v-model="account.createdAt">
</p>
<p>
<label for="lastModifiedAt">Last Modified At</label>
<input type="text" id="lastModifiedAt" v-model="account.lastModifiedAt">
</p>
<input type="reset" value="Clear" #click="reset">
<input type="submit" value="Save User 🐱">
</form>
</div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.10/dist/vue.js"></script>
<script>
const API = 'http://localhost:3000/api/Account/';
let AccountApp = new Vue({
el: '#AccountApp',
data: {
accounts: [],
account: {
id: '',
email: '',
createdAt: '',
lastModifiedAt: ''
}
},
created: function () {
this.getAccounts();
},
methods: {
getAccounts: function () {
fetch(API)
.then(res => res.json())
.then(res => this.account = res);
},
storeAccount: function () {
let method;
console.log('storeAccount', this.account);
// Handle new vs old
if (this.account.id === '') {
delete this.account.id;
method = 'POST';
} else {
method = 'PUT';
}
fetch(API, {
headers: {
'Content-Type': 'application/json'
},
method: method,
body: JSON.stringify(this.account)
})
.then(res => res.json())
.then(res => {
this.getAccounts();
this.reset();
});
},
deleteAccount: function (c) {
fetch(API + c.id, {
headers: {
'Content-Type': 'application/json'
},
method: 'DELETE'
})
.then(res => res.json())
.then(res => {
this.getAccounts();
});
// call reset cuz the cat could be 'active'
this.reset();
},
editAccount: function (c) {
/*
This line was bad as it made a reference, and as you typed, it updated
the list. A user may think they don't need to click save.
this.cat = c;
*/
this.account.id = c.id;
this.account.email = c.email;
this.account.createdAt = c.createdAt;
this.account.lastModifiedAt = c.lastModifiedAt;
},
reset: function () {
this.account.id = '';
this.account.email = '';
this.account.createdAt = '';
this.account.lastModifiedAt = '';
}
}
});
</script>
Here is the screenshot when i run the applications .
Here is the screenshot on Networks tab ..
I have a AngularJS app where I take in user input and store it in a painting objects and then send it to my spring boot back-end that will store it to the Mongodb server and return an id, however when I try go POST anything to the server i get an empty response back, even though the object gets stored in the server.
AngularJS code:
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.1/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
<br>
<br>
<br>
URL : <input type="text" ng-model="painting.url"><br>
Artist : <input type="text" ng-model="painting.artist"><br>
ArtistInfo : <input type="text" ng-model="painting.artistInfo"><br>
Title : <input type="text" ng-model="painting.title"><br>
Dated : <input type="text" ng-model="painting.dated"><br>
Medium : <input type="text" ng-model="painting.medium"><br>
Dimensions : <input type="text" ng-model="painting.dimensions"><br>
Credit : <input type="text" ng-model="painting.credit"><br>
<button ng-click="submit()">Post</button>
<pre>{{painting | json}}</pre>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope','$http', function($scope,$http) {
$scope.name = "";
$scope.painting = {
url: '',
artist: '',
artistInfo: '',
title: '',
dated: '',
medium: '',
dimensions: '',
credit: ''
};
$scope.submit = function(){
console.log(JSON.stringify($scope.painting));
$http({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: 'http://localhost:8080/paintings',
data: $scope.painting
}).then(function (response) {
console.log(response);
}, function (response) {
console.log("Error");
console.log((JSON.stringify(response)));
});
//$http.post('http://localhost:8080/paintings', $scope.painting).catch(console.error);
};
}]);
</script>
</body>
</html>
SpringBoot Java POST Method:
#RequestMapping(method = RequestMethod.POST, value = "/paintings")
public String save(#RequestBody Painting painting){
repository.save(painting);
System.out.println("Function called");
return painting.getID();
}
PostMan Response:
Not sure why I'm getting an empty response when I check the console in a browser, even though the server is sending back a response.
I think you need to access the data property of the response,
.then(function (response) {
console.log(response.data);
}
What I ended up doing with the help of #Sajeetharan is edit my backend post request to
#RequestMapping(method = RequestMethod.POST, value = "/paintings")
public ResponseEntity<String> save(#RequestBody Painting painting){
repository.save(painting);
System.out.println("Function called");
JSONObject json = new JSONObject();
json.put("id",painting.getID());
return ResponseEntity.ok(json.toString());
}
How can I pass the information from an input field in the front end(using angularjs) as a JSON object to a server(javascript)?
Basically what I intend to do is take input from a user, and pass it as a query to search a database and return the values.
My controller code:
`app.controller('SearchController',['$scope','$http',function($scope,$http){
$scope.click=function(){
var data=$scope.query1;
$http.post('/credjson',data);
/*$scope.addRowAsyncAsJSON = function(){
$scope.cred.push({ 'query':$scope.query1 });
var dataObj = {
query : $scope.query1,
};
var res = $http.post('/credjson', dataObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
});
res.error(function(data, status, headers, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
$scope.query1='';*/`
Note: The code in between /* */ was a different attempt at trying this out.
My view code:
`<div style="padding-top:20px" ng-controller="SearchController">
<form name="form1" ng-submit="click()">
<input id="creditq" ng-model='query1' type="text" />
<button id="Search" ng-value='Search'>Search</button><br/><br/>
</form>
</div>`
Just construct your JSON payload and pass it to $http as the second param
data: { query1: $scope.query1 }
and then
$http.post('/credjson',data);