有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javascript使用Fetch API时在后端没有输出

我想使用fetchapi将数据从浏览器发送到后端

HTML:

<form action="#" id="comment-form">
   <div class="comment-enter-field">
         <textarea placeholder="Write a comment..." class="comment-input" name="comment-input"></textarea>
         <div class="comment-footer">
            <input type="submit" value="Comment" class="comment-submit">
         </div>
   </div>
</form>

JavaScript:

// Submitting the form
const commentData = new URLSearchParams();
const commentInput = document.querySelector('.comment-input');
const sessionData = JSON.parse(sessionStorage.getItem('userEntity'));
// Append all the data that we need
commentData.append('comment', commentInput.value);
commentData.append('data', sessionData);

document.getElementById('comment-form').addEventListener('submit', (e) => {
    e.preventDefault();
    console.log(commentInput.value); // This outputs the correct string that I would like to be shown in backend
    fetch('../comments', {
        method: 'POST',
        body: commentData
    })
});

Java:

@WebServlet("/comments")
public class Comments extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getParameter("comment"));
    }
}

我只想得到commentInput.value的值,但奇怪的是System.out.println(req.getParameter("comment"));什么也不返回System.out.println("Hello world");工作,但req.getParameter("comment")不返回任何内容,甚至不返回错误。我做错了什么


共 (0) 个答案