简体   繁体   中英

Headers not set node.js api push notification

Hello im trying to set up push notifications for my webapp.

I'm getting my subscription like I should.

It saves it to my database correctly.

It sends my notification like it should if there only is ONE user in the db

and i want to send to more than only one user :)

Im using:

  • Vue.js (framework)

  • Axios (post)

  • node.js (api)

  • mongoDB (database)

Here's my post to API.

await axios({
          method: 'post',
          url: 'API',
          data: {
            subscription: JSON.stringify(subscription),
            storeId: storeId
          },
          headers: {
            'Content-Type': 'application/json'
          }
        })

It registreres my post, but then i get an throw error. that "Can't set headers after they are sent."

I'm using CORS in my app like this:

const cors = require('cors')

const app = express();
app.use(bodyParser.json());
app.use(cors())
app.use(morgan('combined'))

The way I'm handling the post from my website is by finding my subscriptions and then map through and say foreach subscription

webpush

//subscribe routes
app.post('/pushNotification', (req, res) => {
  var storeId = req.body.storeId
  res.setHeader('Content-Type', 'application/json');
  console.log(storeId)
  if (req.body.storeId != null) {
    console.log('Test1')
    //get pushSubscription object

    //create payload
    const payload = JSON.stringify({ title: 'push test' })
    Push.find({
      "storeId": storeId
    },
    'subscription', function(error, response) {
      console.log('Test2')
      console.log(response)
      response.map(item => {
        res.status(201).json({});
        console.log('Test3')
        var subscription = item.subscription
        console.log(subscription)
        webpush.sendNotification(subscription, payload).catch(err => console.error(err));
      })
    })
  } else {
    res.send("failed")
  }
})

As i can read around somewhere is it im not setting headers or something right. I have used cors like in tutorials and stuff.

So it's like it is crashing because it iterates wrong. but i can't see how.

ERROR MESSAGE:

错误信息

Thanks in advance

您会收到此错误,因为res.status(201).json({})已经设置了标头并将响应发送回客户端,但是webpush.sendNotification也试图设置标头。您应该仅使用webpush.sendNotification(subscription, payload).catch(err => console.error(err));

res.json([body]) sets the corresponding header and sends the result:

Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().

So, first of all you don't need to set header manually. second, If the response has more than one item, since you can't send multiple result for a request, you shouldn't use res.json in a map . Moreover, be aware of webpush.sendNotification that it may send a result too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM