初识axios,跟着网上老师一步一步进行,所有代码都一样,但是执行的时候却不能得出结果,前后端无法建立连接,前端后台都没有反应
前端代码:
<script src="js/axios-0.18.0.js"></script>
<script>
axios({
method: "get",
url: "http://localhost:8080/ajax-demo/axoisServlet?username=zhangsan",
}).then(function (resp) {
alert(resp.data);
});
</script>
servlet的代码:
package com.itheima.controll;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/axoisServlet")
public class AxoisServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get....");
String username = req.getParameter("username");
System.out.println(username);
resp.getWriter().write("msg:haha");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
执行后,结果如下
排查了好长时间,也没找到原因,后来看到一张帖子,需要在发送axios时加上一行代码
headers: {'Content-type': 'application/x-www-form-urlencoded'}
整体是这个样子的
<script src="js/axios-0.18.0.js"></script>
<script>
axios({
method: "get",
url: "http://localhost:8080/ajax-demo/axoisServlet?username=zhangsan",
headers: {'Content-type': 'application/x-www-form-urlencoded'}
}).then(function (resp) {
alert(resp.data);
});
</script>
最后执行成功。
具体原因不知。