req.body.tweet返回值并且没有防御

时间:2018-12-17 10:46:18

标签: javascript node.js express twitter

当我想将高音发布到高音扬声器时,我正在使用app.post。 但是,当我使用req.body.tweetMessage时,我得到了tweet值和“ undifiend”。我只想要tweet值,而我不断 body.tweetMessage:“ tweet的值” body.tweetMessage:未定义 这是为什么?我该如何解决?

app.js

let express = require("express");
let bodyParser= require ("body-parser");
let app = express();
let path = require("path");

let Twitter = require('twitter');
let config = require('./config.js');
let twitter = new Twitter(config);
let username = "NaouriRavid";


app.use(bodyParser.urlencoded({extended:false}));

app.use(bodyParser.json());


app.get('/',function(req,res){
res.sendfile("client.html");
});


app.get('/logo.png',function(req,res){
res.sendfile("logo.png");
});

// Post a tweet
app.post("/", function (req, res) {
if(req.body) {
    let tweet = (req.body.tweetMessage); // Get the user's tweets value from client
    **console.log("body.tweetMessage:"+req.body.tweetMessage);**
    let params = {
        status: tweet
    }
    twitter.post('statuses/update', params, function(err, data, res) {
        if(!err){
            let username = data.user.screen_name;
            let tweetId = data.id_str;
            console.log('your tweet have been posted! you can find it here:', `https://twitter.com/${username}/status/${tweetId}`);
        } else {
            console.log(err);
        }
    })
    res.status(200).send("your tweet have been posted! you can find it here:" +" "+`https://twitter.com/${username}`);
}
else {
    res.status(404).send({error: "There was a problem posting the tweet"})
}
});


app.listen(8081 ,function(){
console.log("Live at Port " + 8081);
});

client.html

<script>
document.getElementById("tweet").addEventListener("click", function()
{
    let tweet = document.getElementById("tweetMessage").value;
    let json = JSON.stringify({"tweetMessage": tweet});
    var xhr = new XMLHttpRequest();
    var url = 'http://localhost:8081';
    if (tweet === '') {
        alert("You must write something!");
        return;
    }
    else {
        xhr.open("POST", url, true); // true = asynchronous
        xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        xhr.send(json);
    }
});

</script>

1 个答案:

答案 0 :(得分:0)

尝试使用表单数据

<script>
document.getElementById("tweet").addEventListener("click", function()
{
    let tweet = document.getElementById("tweetMessage").value;
    var formData = new FormData();
    formData.append('tweetMessage',tweet);

    var xhr = new XMLHttpRequest();
    var url = 'http://localhost:8081';
    if (tweet === '') {
        alert("You must write something!");
        return;
    }
    else {
        xhr.open("POST", url, true); // true = asynchronous
        xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        xhr.send(formData);
    }
});

</script>