2017-05-02 28 views
0

我創建了哈皮一個簡單的API,有我可以張貼到的路由,它看起來像這樣:使用JavaScript提取API與哈啤

server.route({ 
    method: "POST", 
    path: "/hello", 
    handler: function(request, reply) { 
    // It doesn't ever get to here 
    return reply({hello: request.payload.name}); 
    }, 
    config: { 
    validate: { 
     payload: { 
     name: Joi.string().required() 
     } 
    } 
    } 
}); 

我可以成功發送POST請求到郵差這條道路: Postman Request 它返回預期的響應。但是,當我使用這段JavaScript發送請求時:

fetch("http://localhost:1111/hello", { 
    mode: "cors" 
    body: {name: "John Doe"} 
}).then(() => { 
    console.log("yay! it worked"); 
}); 

這失敗了,並說「值」必須是一個對象。

回答

0

事實證明,我只是需要先在字符串化JSON,然後它的工作:

fetch("http://localhost:1111/hello", { 
    mode: "cors" 
    body: JSON.stringify({name: "John Doe"}) 
}).then(() => { 
    console.log("yay! it worked"); 
});