I have a problem typing a data request to api. I use laravel vue and axios to make a request. the following problem appears
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
file: "/var/www/html/accurate/ibn_accurate_web_api/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
line: 383
message: "CSRF token mismatch."
<script>
import axios from "axios"
// import pagination from 'laravel-vue-pagination'
export default {
name: "branch-list",
components: {
// pagination
},
data() {
return {
branch: {
type: Object,
default: null
}
}
},
mounted() {
this.list()
},
methods: {
async list(page = 1) {
await axios.post("http://ibn.tes/api/accurate/branch", {
code_database: 550724,
headers:{
"X-CSRF-TOKEN": window.Laravel.csrfToken
}
}).then(({ data }) => {
this.branch = data
console.log(data);
}).catch(({ response }) => {
console.error(response)
})
}
}
}
</script>
Related
In the following postman pre request script, I need to call multiple requests before I make an actual postman request.
Firstly, it will call session API to retrieve the session id
After session id is success only, then I need to call customer signon to make the user logged in.
So I did the following changes in my postman prerequest script but some how the LocalSessionId in the customer signon request is undefined.
const sessionRequestData = {
url: "http://myurl.com/session",
method: 'POST',
header: { 'content-type': 'application/json' },
body: {
mode: 'raw',
raw: JSON.stringify({
"device": {
"id": "web",
"type": "WEB"
}
}
};
pm.sendRequest(sessionRequestData, function (err, res) {
var jsonData = res.json();
if (err) {
console.log("mailman: error retrieving session id"+err);
}
else {
console.log("mailman: retrieved session data succesfully"+ jsonData.session.id);
pm.variables.set("LocalSessionId", jsonData.security.session.id);
}
});
const customerSignonRequestData = {
url: "http://myurl.com/CustomerSignOn",
method: 'POST',
header: { 'content-type': 'application/json' },
body: {
mode: 'raw',
raw: JSON.stringify( "customerRequest": {
"identities": {
"identity": [
{
"data": "sessionId",
"value": `${pm.variables.get("LocalSessionId")}`
}
]
}
});
pm.sendRequest(customerSignonRequestData, function(err, res){
console.log("customer sign on request "+ JSON.stringify(customerSignonRequestData.body.raw))
var jsonData = res.json();
if (err) {
console.log("mailman: unable to signon"+err);
} else {
console.log("mailman: login successful"+ JSON.stringify(jsonData))
}
});
Can anyone suggest how can I make sure that the customer signon is called after the session is retrieved only.
Hi guys im working on an angular project with a java (spring boot) backend and sql server for database,i have a method that uses "Get" but im getting the following error:
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 200
statusText: "OK"
url: "http://localhost:8080/admin/allcompanies/02ff0785-3739-4f8d-b77f-eff6b77954f8"
ok: false
name: "HttpErrorResponse"
message: "Http failure during parsing for http://localhost:8080/admin/allcompanies/02ff0785-3739-4f8d-b77f-eff6b77954f8"
error: {error: SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at XMLHttpRequest.onL…, text: "[{"id":2,"name":"Comp2","password":"comp2","email"…lcompanies/02ff0785-3739-4f8d-b77f-eff6b77954f8"}"}
__proto__: HttpResponseBase
Ive tried adding {responseType: 'arraybuffer'})/text/blob but im getting a compliation error
error TS2322: Type '"arraybuffer"' is not assignable to type '"json"'.
code snippits:
relevant service:
#Injectable({
providedIn: 'root'
})
export class AdminService {
constructor(private client: HttpClient) { }
public getAllCompanies(): Observable<Company[]>{
return this.client.get<Company[]>("http://localhost:8080/admin/allcompanies/" + sessionStorage.token);
}
method component:
#Component({
selector: 'app-get-all-companies',
templateUrl: './get-all-companies.component.html',
styleUrls: ['./get-all-companies.component.css']
})
export class GetAllCompaniesComponent implements OnInit {
public companies : Company[]=new Array();
constructor(private client:AdminService) { }
ngOnInit() {
this.client.getAllCompanies().subscribe(companies => {
this.companies=companies;
});
}
}
my routing:
const routes: Routes = [
{path: "login", component: LoginComponent},
{path: "admin", component : AdminComponent},
{path:"home",component:HomeComponent},
{path:"addcomp",component:AddCompanyComponent},
{path:"updatecomp",component:UpdateCompanyComponent},
{path:"deletecomp",component:DeleteCompanyComponent},
{path:"allcompanies",component:GetAllCompaniesComponent},
{path:"company",component:GetOneCompanyComponent},
{path:"", redirectTo: "home", pathMatch: "full"}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
and my backend controller:
#CrossOrigin(origins = "http://localhost:4200")
#RestController
#RequestMapping("admin")
public class AdminController {
#Autowired
Map<String, Session> sessionsMap;
#GetMapping("/allcompanies/{token}")
public ResponseEntity<Object> getAllCompanies(#PathVariable String token) {
Session session = sessionsMap.get(token);
if (session != null) {
// session.setLastAccessed(??);
AdminFacade facade = (AdminFacade) session.getFacade();
return ResponseEntity.ok(facade.getAllCompanies());
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized login");
}
}
Vue.js:
created() {
axios.get('/people')
.then((response) => {
this.people = response._embedded.data.people
})
.catch((error) => {
console.log(error)
})
},
GET request response according to chrome network: https://pastebin.com/bDmKQFgB
Console log:
error
App.vue?234e:298 ReferenceError: _this is not defined
at eval (App.vue?234e:294)
The second line comes from the catch() part.
Where the json comes from: Java Spring Backend with mongodb like: https://spring.io/guides/gs/accessing-mongodb-data-rest/
this is under a different context within the Axios promise. Try tying this to a variable outside of the Axios promise:
Codepen mirror: https://codepen.io/oze4/pen/EJWdLr
new Vue({
el: "#app",
data: {
title: ""
},
methods: {
getData() {
this.title = "Loading...";
/* ============================ */
/* THIS IS WHAT YOU NEED TO ADD */
/* ============================ */
var vm = this;
/* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */
/* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */
axios
.get("https://jsonplaceholder.typicode.com/todos/1")
.then(function(response) {
/* IN USE: */
vm.title = response.data.title;
})
.catch(function(error) {
alert(error);
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<div id="app">
<button #click="getData">Click to load data from api</button>
<p>{{ title }}</p>
</div>
I'm trying to develop a small application to create index on local elasticsearch engine. I use angularjs on the front-end, and spring-boot on the back-end. It can create index successfully, however, when I want to retrive the response in the front-end, it keeps throwing me errors.
Below is my AngularJS api call:
app.service('ESIndexService', function($http) {
this.createESIndex = function(esindexObj) {
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj
};
return $http(settings).then(function(response) {
console.log("response:"+response);
return response;
}, function(error) {
console.log("error:"+error);
return error;
});
};
});
Then this is my controller:
#CrossOrigin
#RestController
#RequestMapping(value = "ESIndex")
public class ESIndexController {
#RequestMapping(value = "createESIndex", method = RequestMethod.POST)
public #ResponseBody String createIndex(#RequestBody ESIndex esIndex) {
try {
Settings settings = Settings.builder()
.put("xpack.security.user", String.format("%s:%s", Constants.ES_UNAME, Constants.ES_PWD)).build();
TransportClient client = new PreBuiltXPackTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(Constants.ES_HOST), Constants.ES_PORT));
CreateIndexResponse response = client.admin().indices().prepareCreate(esIndex.getName()).setSettings(Settings.builder()
.put("index.number_of_shards", esIndex.getNumberOfShards())
.put("index.number_of_replicas", esIndex.getNumberOfReplicas())).get();
client.close();
if(response.isAcknowledged() && response.isShardsAcked())
return Constants.SUCCESS;
else
return "Fail to create index!";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
I want to get the response status and data in AngularJS response. However, it keeps throwing me errors:
error:SyntaxError: Unexpected token i in JSON at position 0
I'm not using JSON.parse function, why it gives me error like this?
After adding responseType: 'text', still throwing same error, the chrome nextwork
It turns out I need to add "transformResponse: undefined", however, in another of my project, I never did this. What's the difference?
AngularJS:
this.newBlog = function(blogObj) {
var settings = {
method: 'POST',
url: baseUrl + "/blog/newBlog.do",
data: blogObj
}
return $http(settings).then(function(response) {
return response;
}, function(error) {
return error;
});
};
Java Controller:
#RequestMapping(value="newBlog.do", method=RequestMethod.POST)
public #ResponseBody String newBlog(#RequestBody Blog blog, HttpServletRequest request) {
User createdBy = (User) request.getSession().getAttribute("user");
if(createdBy == null)
return NO_SESSION_MSG;
else {
createdBy.setPwd(null);
blog.setCreatedAt(TQBUtilities.getCurrentTime());
blog.setLastUpdatedAt(TQBUtilities.getCurrentTime());
blog.setCreatedBy(createdBy);
return blogService.newBlog(blog);
}
}
Angular is automatically trying to parse the server response as JSON. Try adding this to your settings object
responseType: 'text'
So
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj,
responseType: 'text'
};
#jheimbouch add "transformResponse: undefined" to http call, like below, works fine:
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj,
transformResponse: undefined
};
However, why it is required in angularjs 1.6.2? When I was using AngularJS 1.4.8, I don't need to add transformResponse attributes.
I am trying to connect a Java REST service to a ExtJs JSONP request but even though the java method executes I haven't been able to get a response test. This is what I am trying:
Java Code:
#Path("/hello")
public class Hello {
#GET
#Produces("text/javascript") // have also tried application/json
public String sayJsonHello(#QueryParam("_dc") String dcIdentifier, #QueryParam("callback") String callback) {
System.out.println(callback);
callback += "({\"success\":true, \"msj\":" + "\"" + "Exitoooo!" + "\" });";
System.out.println(callback);
return callback;
}
}
ExtJs code:
Ext.data.JsonP.request({
url: "http://10.1.50.66:7001/Simulador/webresources/hello",
params: {
},
callback: function (response) {
console.log(response); //true
console.log(response.result); //undefined
console.log(response.responseText); //undefined
console.log(response.success); // undefined
if (response.success === true) {
Ext.Msg.alert('Link Shortened', response.msj, Ext.emptyFn);
} else { // entering here :( why ?
Ext.Msg.alert('Error', response.msj, Ext.emptyFn);
}
}
});
response is printting true, everything else undefined :(
callback looks like this Ext.data.JsonP.callback1({"success":true, "msj":"exito"})
Any ideas what could be wrong?
Ok this worked out for me:
Ext.data.JsonP.request({
url: "http://10.1.50.66:7001/Simulador/webresources/hello",
callbackKey: 'callback1',
params: {
},
success : function(response) {
console.log("Spiffing, everything worked");
// success property
console.log(response.success);
// result property
console.log(response.result);
console.log(response.msj);
},
failure: function(response) {
console.log(response);
Ext.Msg.alert('Error', 'Please try again.', Ext.emptyFn);
}
});