在ember-js中使用response.json()从API获取响应时显示错误



我必须创建一个web应用程序来在mySQL数据库中添加用户,并使用ember-js实现UI。

app/components/user.hbs

<h1>User Management!</h1>
<div>   
<label1>User Id </label1>   <colon1>:</colon1>
<input1>{{input type="text" value=id placeholder="Enter id"}}</input1>
<label2>Firstname</label2>  <colon2>:</colon2>
<input2>{{input type="text" value=firstname placeholder="Enter firstname"}}</input2>
<label3>Lastname</label3>   <colon3>:</colon3>
<input3>{{input type="text" value=lastname placeholder="Enter lastname"}}</input3>
<label4>Mail Id</label4>    <colon4>:</colon4>
<input4>{{input type="text" value=mailid placeholder="Enter mailid"}}</input4>
</div>
<button1 {{on "click" (fn this.user "add" id firstname lastname mailid )}}>Add User</button1>
<button2 {{on "click" (fn this.user "delete" id firstname lastname mailid )}}>Delete User</button2>

app/components/user.js

import Component from '@glimmer/component';
import {action} from "@ember/object";
import {tracked} from "@glimmer/tracking";
export default class UserComponent extends Component {
@action 
async user (type,id,firstname,lastname,mailid){
let response=await fetch("http://localhost:8080/UserManagement/UserManagementServlet",
{   method: "POST",
mode:"no-cors",
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({
"type": type,
"id": id,
"firstname":firstname,
"lastname":lastname,
"mailid":mailid
})
});
let parsed=await response.json();
alert(parsed.status);
}
}

Servlet API代码

//Required Header files
@WebServlet("/UserManagementServlet")
public class UserManagementServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException 
{   res.setContentType("application/json");  
res.setCharacterEncoding("UTF-8");
Gson gson=new Gson();
BufferedReader br=new BufferedReader(new InputStreamReader(req.getInputStream()));
String param=br.readLine();
User user = gson.fromJson(param, User.class);
HashMap<String,String> jsonfile=new HashMap<String,String>();
PrintWriter out=res.getWriter();
String url="jdbc:mysql://localhost:3306/employee",username="root";
String password="root";
Connection con=null;
PreparedStatement pst;
String query="select*from user";
ResultSet rs;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url,username, password);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Entered");
if (user.getType().equals("add")) {
try {
String insertquery="INSERT INTO user" +"  (id,firstname,lastname,  mailid) VALUES " +" (?,?, ?, ?);";
pst = con.prepareStatement(insertquery);
pst.setString(1, String.valueOf(user.getId()));
pst.setString(2, user.getFirstName());
pst.setString(3, user.getLastName());
pst.setString(4, user.getMailid());

jsonfile.put("id", String.valueOf(user.getId()));
jsonfile.put("firstname", user.getFirstName());
jsonfile.put("lastname", user.getLastName());
jsonfile.put("mailid", user.getMailid());
jsonfile.put("status","User Added Successfully");

String final1=gson.toJson(jsonfile);
System.out.println(final1);
out.println(final1);

pst.executeUpdate();   
} catch (Exception e) {
out.println("error"+e);
}
}
out.flush();
}
}

它显示了Cors的错误,所以我添加了";"模式":"没有紧身胸衣";在user.js中,但在那之后cors错误消失了,但这个错误没有。

当点击添加用户按钮时,它在这一行显示一个错误";让解析=等待响应.json((">

user.js:54 Uncaught (in promise) SyntaxError: Unexpected end of input
at UserComponent.user (user.js:54)"

基本上,我可以建议你了解什么是CORS。简而言之,你试图提出一个跨源请求(可能是从http://localhost:4200http://localhost:8080(,然后你必须使用CORS,否则浏览器会出于安全原因阻止它。

然而,这可能不是您想要的。这个问题的出现是因为您运行的是ember开发服务器,因此与后端的来源不同。然而,在生产的后期,这种情况不会发生——你不会在那里运行ember服务器,但可能有一个Web服务器同时为你的后端和前端服务。

对于这种情况(并不总是,但经常是这样(,成员开发服务器具有--proxy选项。因此,您将运行ember serve --proxy=http://localhost:8080,然后它将代理从http://localhost:4200http://localhost:8080的所有AJAX请求。

然后将fetch的URL从"http://localhost:8080/UserManagement/UserManagementServlet"更改为"/UserManagement/UserManagementServlet"。这是因为,如果您不指定原点,而是从/开始,则它始终是当前原点。这也有一个好处,你不必为了生产而改变它。

然后浏览器将请求"http://localhost:4200/UserManagement/UserManagementServlet",它将在没有CORS的情况下工作(也不需要mode:"no-cors"(,成员开发服务器将重定向它。

但是如果您计划在生产中为后端和前端提供单独的服务器,这将不起作用,并且您需要使用CORS。


关于mode:"no-cors"的简要说明。这将始终阻止您读取响应,从而使请求对加载数据毫无用处。这只与发送数据有关。请参阅此处:

JavaScript可能无法访问生成的响应的任何属性。

最新更新