Cannot upload file to Spring Boot REST using Axios and FormData - spring

I try to upload file from page using axios and can't get it on my controller.
In fromt-end I use Vue.js with axios, and at the back end Spring MVC Controller. It seems that my controller can`t convert FormData() to MultipartFile in spring. I read a lot of questions but have no answer. here is my code:
<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- Vue.js development version, includes helpful console warnings -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!--Axios dependency-->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!--Bootstrap-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</head>
<body>
<h4>Uploading files with Vue.js</h4>
<div id="uploadSingle" class="container">
<h5>Single file uploading</h5>
<div class="large-12 medium-12 small-12 cell">
<div class="form-row" >
<div class="col-md-4 mb-3">
<input type="file" ref="file" id="customFile"
v-on:change="handleFileUpload($event)"
class="custom-file-input"
enctype="multipart/form-data">
<label class="custom-file-label" for="customFile">{{chosenFile}}</label>
</div>
</div>
<button v-on:click="submitFile()" class="btn btn-primary">Submit</button>
</div>
</div>
<div id="uploadMultiple" class="container">
<h5>Multiple files uploading</h5>
</div>
<script >
var app = new Vue({
el: '#uploadSingle',
data() {
return {
message: 'Hello Vue!',
singleFile: '',
refFile: '',
chosenFile: 'Chose file'
};
},
methods:{
handleFileUpload(event){
this.singleFile = event.target.files[0];
this.chosenFile=this.singleFile.name;
},
submitFile(){
var formData = new FormData();
formData.append("file", this.singleFile);
axios.post( '/single-file',
formData,{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function(){console.log('SUCCESS!')})
.catch((error) => console.log( error ) )
},
},
})
</script>
</body>
</html>
and controller file:
package com.yurets_y.webdevelopment_uploading_file_with_vue.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
#CrossOrigin("*")
#Controller
public class UploadController {
#Value("${upload.path}")
private String uploadPath;
#ResponseBody
#PostMapping(value="/single-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> uploadSingle(
#RequestParam(name="file", required = false) MultipartFile file
) {
System.out.println("uploaded");
System.out.println(file);
return ResponseEntity.ok().build();
}
}
I will be very grateful for the advice.
P.S.
when I use #RequestParam(name="file", required=true) MultipartFile file I get error POST http://localhost:8080/single-file 400 (Bad Request), It looks like spring cannot get MultipartFile file from FormData. At back end I don't get any errors, only MultipartFile file = null

After two days, that I spent to solve my promlem I fount a couple of working projects, compare all files and found, that my problem was in dependencies,
I used dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
And when I change dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Now it's working exactly how I need.

Related

Thymeleaf is trying to build a html which does not exist and which is not called anywhere

I am trying to build a spring mvc app with spring boot and thymeleaf. I am trying to create a form to insert an object into my data base (something which I already do in my app and is working) but I constantly find this error:
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "ServletContext resource [/WEB-INF/views/error.html]")
(...)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/views/error.html]
(...)
This is the problem you usually find when you are trying to reference a template which does not exist or has a different name. Here's the thing. There is no Error.html in my views' folder as you can see in the print below:
Can anyone help me understand what's going on?
EDIT with more information:
Below you can find the endpoints which are giving me trouble:
#GetMapping("{id}/add-expense")
public String expensesForm(Model model, #PathVariable Long id){
model.addAttribute("expense", new Expenses());
model.addAttribute("budgetId", id);
return "expenseForm";
}
#PostMapping("{id}/add-expense")
public String expenseSubmitted(#ModelAttribute Expenses expense, #PathVariable Long id, Model model){
Budgets budget = budgetsRepository.getById(id);
if(budget != null){
budget.addExpense(expense);
expense.setBudget(budget);
expensesRepository.saveAndFlush(expense);
}
else{
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "not all variables there");
}
model.addAttribute("expense", expense);
return "expenseResult";
}
The GET endpoint seems to be working as intended. When I load the "id/add-expense" path it displays the page "expenseForm" correctly. The problem comes when I try to submit the form in the "expenseForm" template and go to the POST for "id/add-expenses". That is when I get a 400 bad request response. I am lead to believe that the problem might be that the "expenseForm" cannot correctly populate the #ModelAttribute in the POST method but I can't say why or how to fix it. In the console, I am given the error above which tells me that Thymeleaf cannot find the template for "error.html".
expenseForm.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<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">
<title>Expense Creation</title>
</head>
<body>
<div class="container">
<div class="container">
<div th:insert="fragments/navbar.html"> </div>
<div class="jumbotron">
<div class="row">
<h3>Expense Creation</h3>
</div>
<form action="#" th:action="#{/budgets/{id}/add-expense(id = ${budgetId})}" th:object="${expense}" method="post">
<p>Name: <input type="text" th:field="*{expenses_name}" /></p>
<p>Amount: <input type="number" th:field="*{expenses_amount}" /></p>
<p>Date: <input type="text" th:field="*{expenses_date}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</div>
</body>
</html>
expenseResult.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<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">
<title>Expense Creation</title>
</head>
<body>
<div class="container">
<div class="container">
<div th:insert="fragments/navbar.html"> </div>
<div class="jumbotron">
<div class="row">
<h3>Expense Created</h3>
</div>
<p th:text="'Name: ' + ${expense.expenses_name}" />
<p th:text="'Amount: ' + ${expense.expenses_amount}" />
<p th:text="'Date: ' + ${expense.expenses_date}" />
Submit another expense
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="js/budgetScript.js"></script>
</div>
</body>
</html>
Class Expenses:
#Entity(name = "expenses")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Expenses {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long expenses_id;
private String expenses_name;
private Integer expenses_amount;
private Date expenses_date;
#ManyToOne
#JoinTable(
name = "budget_expenses",
joinColumns = #JoinColumn(name = "expenses_id"),
inverseJoinColumns = #JoinColumn(name = "budgets_id"))
private Budgets budget;
//Gettes setters and constructor
}
Thank you in advance.
EDIT 2 after changing the name of "expenseResult.html" to "error.html":
So I decided to follow the tip from andrewJames and I changed the name of "expenseResult.html" to "error.html". I also changed the return value in the POST method from 'return "expenseResult"' to 'return "error"' and I am no longer given the 400 bad request error on the application. Instead, I am given the "error.html" page but the fields for expense.expenses_name, expense.expenses_amount or expense.expenses_date are not shown in the page. It is just an empty page with the "Expense Creation" text. In the console I receive a new error:
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "expense.expenses_name" (template: "error" - line 19, col 16)
(...)
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'expenses_name' cannot be found on null
(...)
From what we can see, the application cannot retrieve the fields from null, meaning that the #ModelAttribute Expenses expense is not returning the correct values from the form page. It more or less confirms my suspicion that the problem was in the modelAttribute but I continue to not know how to correct the problem since I have tried to verify multiple times if everything was okay and I found no issue. I also don't understand why it is looking for a "error.html" file considering that I had no prior mention to such a file in my code and project.
EDIT 3 after using ModelandView intead of ModelAttribute:
Following dsp_user's suggestion. I started by hardcoding the path with "/budgets/10/add-expense" instead of using {id} and the problem remained, which makes me believe that the problem is not the path.
I started using the ModelAndView, as can be shown below, but I continued to have the same problem as before (400 bad request).
#PostMapping("{id}/add-expense")
public ModelAndView expenseSubmitted(#ModelAttribute("expenses") Expenses expenses, #PathVariable Long id, Model model){
System.out.println("here");
Budgets budget = budgetsRepository.getById(id);
if(budget != null){
budget.addExpense(expenses);
expenses.setBudget(budget);
expensesRepository.saveAndFlush(expenses);
}
else{
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "not all variables there");
}
ModelAndView modelAndView = new ModelAndView("expenseResult");
modelAndView.addObject("expense", expenses);
return modelAndView;
}
EDIT 4 to add the Budgets logic:
Budgets:
#Entity(name = "budgets")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Budgets {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long budgets_id;
private String budgets_name;
private String budgets_description;
private Integer budgets_amount;
#OneToMany(mappedBy = "budget")
#JsonIgnore
private List<Expenses> expenses;
#Transient
public float budgets_expense_sum = 0;
//Gettes setters and constructor
}
Budget Creation Endpoints:
#GetMapping("new")
public String budgetsForm(Model model){
model.addAttribute("budget", new Budgets());
return "budgetForm";
}
#PostMapping("new")
public String budgetSubmitted(#ModelAttribute Budgets budget, Model model){
budgetsRepository.saveAndFlush(budget);
model.addAttribute("budget", budget);
return "budgetResult";
BudgetForm.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<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">
<title>Budget Creation</title>
</head>
<body>
<div class="container">
<div class="container">
<div th:insert="fragments/navbar.html"> </div>
<div class="jumbotron">
<div class="row">
<h3>Budget Creation</h3>
</div>
<form action="#" th:action="#{/budgets/new}" th:object="${budget}" method="post">
<p>Name: <input type="text" th:field="*{budgets_name}" /></p>
<p>Description: <input type="text" th:field="*{budgets_description}" /></p>
<p>Monthly Amount: <input type="number" th:field="*{budgets_amount}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</div>
</body>
</html>
BudgetResult.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<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">
<title>Budget Creation</title>
</head>
<body>
<div class="container">
<div class="container">
<div th:insert="fragments/navbar.html"> </div>
<div class="jumbotron">
<div class="row">
<h3>Budget Created</h3>
</div>
<p th:text="'Name: ' + ${budget.budgets_name}" />
<p th:text="'Description: ' + ${budget.budgets_description}" />
<p th:text="'Amount: ' + ${budget.budgets_amount}" />
Submit another message
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="js/budgetScript.js"></script>
</div>
</body>
</html>

I can't show an html page

I have to develop a project for college using Spring. I started watching some tutorials and I can't show an html page. I do the same but it returns only one string.
I'm using visual studio code.
Controller:
package com.example.springteste.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ProductController {
#GetMapping("/formulario")
public String formulario()
{
return "form";
}
}
My view is just inside templates
View:
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<main>
<section id="sectionProduct">
<div>
<div id="sectionProduct-title">
<h1>
Título
</h1>
</div>
<div id="sectionProduct-form">
<form action="">
<div class="sectionProduct-form-inputLabel">
<input type="text" id="title" name="title">
<label for="title">
Título
</label>
</div>
</form>
</div>
</div>
</section>
</main>
</body>
</html>
I believe something is missing. I am a beginner in java and spring
If you want to return a view name from the controller method handler - you have to use #Controller annotation. Also make sure you put your views into the correct directory, according to your view resolver configuration.
About #RestController - as the name suggests, it shall be used in case of REST style controllers i.e. handler methods shall return the JSON/XML response directly to the client rather using view resolvers.
In your case the handler method will return "form" to the client.

how to convert view file in image and return in api in laravel

I am creating an API in laravel. In which, I have to convert blade file into image and should return path of converted image or base64 in api.
I am using html2canvas.
routes are:
$router->POST('savecard', 'HomeController#SaveCard');
$router->get('save-capture/{image_for_save}', 'HomeController#savecapture');
I have to call savecard by POSTMAN and run some code and then I have a blade file template1.blade.php
My controller is:
public function SaveCard(Request $request)
{
$find_edittemplate_id = edittemplate::select('id')->where('user_id','=',$request->user_id)->first();
return view('template1');
}
public function savecapture($image_for_save)
{
$image = $image_for_save;
$image = explode(";", $image)[1];
// Remove base64 from left side of image data
// and get the remaining part
$image = explode(",", $image)[1];
// Replace all spaces with plus sign (helpful for larger images)
$image = str_replace(" ", "+", $image);
// Convert back from base64
$image = base64_decode($image);
$destinationPath = storage_path('uploads/');
file_put_contents($destinationPath,'temp.png',$image);
return response()->json(['CardSave' => $image, 'message' => 'Success'], 201);
}
After view template1 file, I created ajax call for convert image to template1.blade.php.
savecapture() will run on template1.blade.php by ajax
view is:
<!DOCTYPE html>
<html>
<head>
<title>Template One</title>
<link href="{{ url('css/style1.css') }}" rel="stylesheet" />
<link href="{{ url('css/font-awesome.min.css') }}" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<link href="../css/font-awesome.min.css" rel="stylesheet" />
</head>
<body>
<div class="row" id="mydiv_screenshot">
<div class="col-md-12 col-sm-12">
<!-- Logo_Section -->
<div class="row text-center backgroundf0f0f0 pd20">
<div class="logo col-md-6 col-sm-8 col-sm-offset-2 col-md-offset-3">
<img src="{{ url('images/logo.png') }}" alt="Logo" width="100%" height="auto" max-height="130px"/>
</div>
<div class="col-md-12 col-sm-12 businessheadlineblack pdt5">
<h3>Digital Business Card</h3>
</div>
</div>
</div>
</div>
</body>
<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
</html>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
<script>
$(document).ready(function() {
window.scrollTo(0, 0);
html2canvas(document.getElementById("mydiv_screenshot")).then(function (canvas) {
var ajax = new XMLHttpRequest();
var image_data = canvas.toDataURL("image/jpeg", 0.9);
$.ajax({
url: '{{ url("save-capture") }}',
type: 'GET',
data: {"image_for_save": image_data},
success: function(response){
if(response != 0){
//console.log(response);
}else{
//console.log(response);
}
},
async: true
});
});
});
</script>
But It show in postman complete blade file and also not run ajax.
I have to convert blade file into image
Blade files are processed by Laravel on server. There is no direct way to convert them in images.
I have used htmlcanvas in core php. But I have no idea in laravel.
PHP doesn't have this functionality. HtmlCanvas is part of browser DOM. Unless you've used some custom PHP extension, what I think you did was creating the image on browser using javascript/canvas and then send it to the server (which is exactly the way to go with Laravel as well).

Angular2 in visual studio 2017 : run error (Resource not found)

I followed this: https://www.codeproject.com/Articles/1181888/Angular-in-ASP-NET-MVC-Web-API-Part
Error:
My URL - - - > http://localhost/home
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its
dependencies) could have been removed, had its name changed, or is
temporarily unavailable. Please review the following URL and make
sure that it is spelled correctly.
Requested URL: /home
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.7.2110.0
systemjs.config.js
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
'app': 'app',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: 'main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
appcomponent
import { Component } from "#angular/core"
#Component({
selector: "user-app",
template: `
<div>
<nav class='navbar navbar-inverse'>
<div class='container-fluid'>
<ul class='nav navbar-nav'>
<li><a [routerLink]="['home']">Home</a></li>
</ul>
</div>
</nav>
<div class='container'>
<router-outlet></router-outlet>
</div>
</div>
`
})
export class AppComponent {
}
app.routing
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomeComponent } from './Components/home.component';
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
app.module
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
_layout.cshtml
<!DOCTYPE html>
<html>
<head>
<base href="/" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<script src="/node_modules/core-js/client/shim.min.js"></script>
<script src="/node_modules/zone.js/dist/zone.js"></script>
<script src="/node_modules/systemjs/dist/system.src.js"></script>
<script src="/systemjs.config.js"></script>
<script src="../node_modules/angular2/bundles/router.dev.js"></script>
<script>
System.import('app/main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
Need support please
in your systemjs.config.js change 'npm:': 'node_modules/' to 'npm:': '/node_modules/'
No issues in the code. All good. I was requesting a wrong url.
Also one small change in system.config.js
Instead of 'npm:': 'node_modules/', we need to use 'npm:': '/node_modules/'

AJAX + Flask update server request when filling form

On the Flask website there's a tutorial on how to use AJAX and this an example to display the sums of two numbers.
This is the python app
from flask import Flask, render_template, request, jsonify
# Initialize the Flask application
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/_add_numbers')
def add_numbers():
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
if __name__ == '__main__':
app.run(
host="0.0.0.0",
port=int("80"),
debug=True
)
This is the HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"
rel="stylesheet">
<script type=text/javascript>
$(function() {
$('a#calculate').bind('click', function() {
$.getJSON('/_add_numbers', {
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val()
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">How To Manage JSON Requests</h3>
</div>
<hr/>
<div>
<p>
<input type="text" size="5" name="a"> +
<input type="text" size="5" name="b"> =
<span id="result">?</span>
<p>calculate server side
</form>
</div>
</div>
</body>
</html>
I see that with this example one is able to send a request to the server every time one clicks on the link, however, I would like to know if it's possible to skip this step and get the request overtime the text inputted by the user changes.
Yes. It's wasteful of resources, but you could change
$('a#calculate').bind('click', function() { to
$('input[name="a"]').change(function() {
And do the same for input b
Edit:
And, to test AS YOU TYPE:
$('input[name="a"]').on('input',function(e){
or:
$('input[name="a"]').keyup(function(e){

Resources