I have written response.end(), but it seems like didn't work, why?

306 Views Asked by At

I used mongodb with mogoose.js, and uWebSockets.js, here is a get handler:

import { db, User } from "../src/db.js";
import queryString from 'querystring';
import { nanoid } from "nanoid";

export const getUser = (res, req) => {
  const userid = queryString.parse(req.getQuery()).userid;

  if(!userid) {
    res.end('No userid, params error');
    return;
  }
  
  //check if user exists
  User.findOne({ userid }).exec().then((user) => {
    if(user) {
      console.log('User found', user, typeof user);
      res.end('---');
      
    } else {
      User.create({
        userid, messageListId: nanoid(), username: '', password: '', email: '', avatar: '', messageList: []
      }).then((user) => {
        console.log('User created', user);
        res.end('---');
      }).catch((err) => {
        console.log('User create error', err);
        res.end('User create error');
      })
    }

  }).catch((err) => {
    console.log('---something wrong when finding user by userid', err);
    res.statusCode = 500;
    res.end('---something wrong when finding user by userid', err);
  })
  
}

but when i send a request, api test shows "Connection was forcibly closed by a peer" and I got an err in console:

Error: Returning from a request handler without responding or attaching an abort handler is forbidden!

so I try this:

// ....

}).catch((err) => {
    console.log('---somthing wrong when finding user by userid', err);
    res.statusCode = 500;
    res.end('---somthing wrong when finding user by userid', err);
  })
  
// add this line here
res.end()
}

now, when I run api test, it connected successfully, statu code is 200. but server console shows another err:

Error: Invalid access of discarded (invalid, deleted) uWS.HttpResponse/SSLHttpResponse. (at res.end('---somthing wrong when finding user by userid', err);)

And, strangely, I can still read the "User found {...}" by code "console.log('User found', user, typeof user);"

OK, what mistakes I make? help me! thanks a lot~

0

There are 0 best solutions below