mardi 20 avril 2021

Showing error while using response.json() in ember js to fetch response from API

I have to create a web app to add a user in mySQL Database and implement UI using ember js.

app/components/user.hbs

   <h1>User Management!</h1>
<div>   
    <label1>User Id </label1>   <colon1>:</colon1>
    <input1></input1>
    <label2>Firstname</label2>  <colon2>:</colon2>
    <input2></input2>
    <label3>Lastname</label3>   <colon3>:</colon3>
    <input3></input3>
    <label4>Mail Id</label4>    <colon4>:</colon4>
    <input4></input4>
</div>
    <button1 >Add User</button1>
    <button2 >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 code

//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();
    }
}

It showed Cors error so I added "mode":"no-cors" in user.js but after that cors error got disappeared but this error didn't.

While Clicking Add User Button, it shows an error in this line " let parsed=await response.json();"

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



Aucun commentaire:

Enregistrer un commentaire