当前位置: 首页 > 知识库问答 >
问题:

JPA函数不能访问REST@PutMapping url

白子昂
2023-03-14

我,一个教授和我的项目组的三个还没能解决这个问题,所以我真的希望这个能成功。

我们正在用JPA和REST构建一个spring boot项目。

createActivity()和updateActivity()的输出格式相同,REST功能也几乎相同,因此在调用updateActivity()函数时出现415(错误的mediatype)错误对我来说是没有意义的。

updateActivity()函数在Postman中工作。

调试的结论是它从未接收到@PutMapping,我无论如何也弄不清原因。

如果你需要更多的信息,请说出这个词。

null

const title = document.getElementById("title-update");
const description = document.getElementById("description-update");
const price = document.getElementById("price-update");
const minHeight = document.getElementById("minHeight-update");
const minAge = document.getElementById("minAge-update");
const equipment = document.getElementById("equipment-update");
const imageLink = document.getElementById("imageLink-update");

function submitForm(){
    if (!event.preventDefault()) {
        createActivity();
    }
}

function createActivity() {

    let activity = {
            "title": document.getElementById("title").value,
            "description": document.getElementById("description").value,
            "price": document.getElementById("price").value,
            "minHeight": document.getElementById("minHeight").value,
            "minAge": document.getElementById("minAge").value,
            "equipment": document.getElementById("equipment").value,
            "imageLink": document.getElementById("imageLink").value,
        }
    console.log(activity);
    let body1 = JSON.stringify(activity);

    addActivity(body1)
}

function addActivity(body1) {
    const createActivityUrl = "http://localhost:8080/newActivity";

    const requestObject = {
            headers:{
                'Content-type': 'application/json',
            },
            method: 'POST',
            body: body1
        };

    console.log(body1);
    console.log(requestObject);

    fetch(createActivityUrl, requestObject)
        .then(response => response.json())
        .then(data => {
            console.log("Succes: ", data);
        })
        .then(alert("Aktiviteten er gemt"))
        .then(location.reload())
        .catch((error) =>{
            console.log("Error: ", error);
        })
}

let list = getAllActivities().then(x => list = x);

const dropdownAllActivities = document.getElementById("dropdownAllActivities");

async function getAllActivities() {
    const url = "http://localhost:8080/findAllActivities"
    const response = await fetch(url);
    const data = await response.json();

    dropdownAllActivities.length = 0;

    data.forEach(x => {
        let element = document.createElement("option");
        element.value = x.activityId;
        element.setAttribute('class', 'updateActivityClass');
        element.textContent = x.title;
        dropdownAllActivities.appendChild(element)
    })

    return data;
}

dropdownAllActivities.addEventListener('change', x => {
    title.value = list[dropdownAllActivities.selectedIndex].title;
    description.value = list[dropdownAllActivities.selectedIndex].description;
    price.value = list[dropdownAllActivities.selectedIndex].price;
    minHeight.value = list[dropdownAllActivities.selectedIndex].minHeight;
    minAge.value = list[dropdownAllActivities.selectedIndex].minAge;
    equipment.value = list[dropdownAllActivities.selectedIndex].equipment;
    imageLink.value = list[dropdownAllActivities.selectedIndex].imageLink;
});

function updateSubmit() {
    if(!event.preventDefault()) {
        updateActivity();
    }
}

function updateActivity() {

    let updatedActivity = {
        "activityId": list[dropdownAllActivities.selectedIndex].activityId,
        "description": document.getElementById("description-update").value,
        "equipment": document.getElementById("equipment-update").value,
        "imageLink": document.getElementById("imageLink-update").value,
        "minAge": document.getElementById("minAge-update").value,
        "minHeight": document.getElementById("minHeight-update").value,
        "price": document.getElementById("price-update").value,
        "title": document.getElementById("title-update").value
    }

    let updateActivityStringified = JSON.stringify(updatedActivity);

    updateDB(updateActivityStringified);
}

function updateDB(updateActivityStringified) {
    const putUrl = "http://localhost:8080/updateActivity";

    const putObject = {
        header: {'Content-type': 'application/json'
        },
        method: 'PUT',
        body: updateActivityStringified
    }

    console.log(putObject)

    fetch(putUrl, putObject)
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Create New Activity</title>
    <link rel="stylesheet" href="./static/styles.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
    <link rel="stylesheet" href="./static/bootstrap.min.css">
    <script type="text/javascript" th:src="@{/js/crud_activity.js}" defer></script>
</head>
<style>
    .center-screen
    {
        display: flex;
        flex-direction: column;
        justify-content: center;
        text-align: center;
        min-height: 25vh;
    }

    .update-activity
    {
        display: flex;
        flex-direction: column;
        justify-content: center;
        text-align: center;
        min-height: 25vh;
    }
</style>

<body>

<div class="center-screen">
    <h1>Ny aktivitet</h1>

    <form id="createForm" enctype="application/json" method="post"  action="/newActivity" onsubmit="submitForm()">
        <input id="title" type="text" placeholder="Titel" required/>
        <br>
        <input id="price" type="number" placeholder="Pris" step=".01" required/>
        <br>
        <input id="minHeight" type="number" max="250" placeholder="Højdekrav" required/>
        <br>
        <input id="minAge" type="number" max="110" placeholder="Alderskrav" required/>
        <br>
        <input id="equipment" type="text" placeholder="Udstyr" required/>
        <br>
        <input id="description" type="text" placeholder="Beskrivelse" required/>
        <br>
        <input id="imageLink" type="text" placeholder="Link" required/>
        <br>
        <input id="save" type="submit" value="Gem"/>
    </form>


<select id="dropdownAllActivities"></select>

<div class="update-activity">
    <h1>Update Activity</h1>
    <form id="update-activity" enctype="application/json" method="post" action="/updateActivity" onsubmit="updateSubmit()">
        <input id="title-update" type="text" placeholder="Titel" required/>
        <br>
        <input id="price-update" type="number" placeholder="Pris" step=".01" required/>
        <br>
        <input id="minHeight-update" type="number" max="250" placeholder="Højdekrav" required/>
        <br>
        <input id="minAge-update" type="number" max="110" placeholder="Alderskrav" required/>
        <br>
        <input id="equipment-update" type="text" placeholder="Udstyr" required/>
        <br>
        <input id="description-update" type="text" placeholder="Beskrivelse" required/>
        <br>
        <input id="imageLink-update" type="text" placeholder="Link" required/>
        <br>
        <input id="save-update" type="submit" value="Gem"/>
        <input id="delete" type="button" value="Slet"/>
    </form>
</div>
</div>

</body>
</html>

null

RESTController:

package com.adventurealley.aafcro.restcontroller;

import com.adventurealley.aafcro.model.ActivityModel;
import com.adventurealley.aafcro.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin(value = "*")
public class ActivityRestController {

    @Autowired
    private ActivityService activityService;

    @GetMapping("/findAllActivities")
    public List<ActivityModel> findAllActivities()
    {
        return activityService.getAllActivities();
    }

    @PostMapping(value = "/newActivity", consumes = "application/json")
    @ResponseStatus(HttpStatus.CREATED)
    public ActivityModel postActivity(@RequestBody ActivityModel activityModel)
    {
        return activityService.CreateActivity(activityModel);
    }

    @PutMapping(value = "/updateActivity", consumes = "application/json")
    public ActivityModel putActivity(@RequestBody ActivityModel updatedActivity) {
        return activityService.updateActivity(updatedActivity);
    }
}

共有1个答案

汝墨一
2023-03-14

updateDB函数中的header应该是headers

function updateDB(updateActivityStringified) {
    const putUrl = "http://localhost:8080/updateActivity";

    const putObject = {
        headers: {'Content-type': 'application/json'
        },
        method: 'PUT',
        body: updateActivityStringified
    }

    console.log(putObject)

    fetch(putUrl, putObject)
}
 类似资料:
  • 问题内容: 我正在编写一个简单的程序来测试基本的GUI。该程序在屏幕中间打印一个字母,并允许用户使用箭头键移动它。一切正常,但是当我尝试在程序开始时将字母居中时,似乎and 函数未返回正确的数字。 这是包含我的Panel类的代码片段 为什么我和函数返回“ 0”? 谢谢你的帮助 问题答案: 我不能说出原因,但: 避免这种情况的一种方法是重写函数并返回您的首选大小。

  • 编译器为自动为所有的public的状态变量创建访问函数。下面的合约例子中,编译器会生成一个名叫data的无参,返回值是uint的类型的值data。状态变量的初始化可以在定义时完成。 pragma solidity ^0.4.0; contract C{ uint public c = 10; } contract D{ C c = new C(); functi

  • 上面的代码在我的主方法中。被注释掉的行抛出错误“无法在类车辆中找到符号”。我正在从一个文件中读取并将信息放置到正确的对象数据字段中。数组是车辆数组。根据我的理解,车辆数组的一个元素可以是车辆或车辆的任何子类。Getters和setters方法可用于每个相应的类和子类,使用父类的Getters和setters。汽车是车辆的一个子类。当我刚刚创建car对象时,为什么不在尝试vehicle之前先尝试访问

  • 并非所有成员函数都要用 public 指定为类接口的一部分。有些成员函数保持 private,作为类中 其他函数的工具函数(utility function)。 软件工程视点 6.17 成员函数分为几大类:读取和返回私有数据成员值的函数、设置私有数据成员值的函数、实现类特性的 函数和进行各种类操作的函数(如初始化类对象、指定类对象、将类与内部类型或其他类进行相互转换以及处理奥对象内存)。 访问函数

  • 按照惯例,访问函数以这样的方式命名:get + 变量的名字。返回值类型通常是对应的变量的类型。 在这个例子中,访问函数可以让我们在得到某个值前确保该值是有效的。函数getReal如下: double Complex::getReal () { if (cartesian == false) calculateCartesian (); return real;

  • 问题内容: 我想知道如何访问另一个函数中的一个函数。我看到了这样的代码: 那么,还有另一种方法来调用该 函数吗?我的第二个问题是,为什么在最后一行中我不打电话? 很好的解释深表感谢。 问题答案: 不,您不能直接调用它,因为它是的局部变量。 您需要使用,因为调用时返回了函数对象。要执行此功能对象,您需要 在这里您可以直接调用它,因为您可以访问它,因为它是由函数返回的。返回的对象实际上称为 闭包, 因