英文:
LongUrl in Node req.params
问题
我想问一下,如何从React前端向Node后端发送包含longUrl参数/值的请求。
这段代码无效。是否有人有这方面的实践经验 - 如果可能的话?
这是React前端
const ulozeniZmen = (event) => {
fetch(
'https://serverWithNodeApp.com/insert/' + id + '/' + name + '/' + longurl, { method: 'POST'}
)
event.preventDefault();
}
这是Node后端
app.post( '/insert/:id/:name/:longurl', function ( req, res ) {
var post = {
id: req.params.id,
name: req.params.name,
longUrl: req.params.longurl,
};
connection.query( "INSERT INTO `test` SET ?", post, ( error, rows ) => {
if( error ) throw error;
if( !error ) {
res.status( 200 ).send(rows);
}
} )
} );
英文:
i would like to ask, how i can send parameter / value with longUrl from React front-end to Node back-end.
This code not work. Have somebody with this practice - if it is possible?
this is React front-end
const ulozeniZmen = (event) => {
fetch(
'https://serverWithNodeApp.com/insert/' + id + '/' + name + '/' + longurl, { method: 'POST'}
)
event.preventDefault();
}
this is Node back-end
app.post( '/insert/:id/:name/:longurl', function ( req, res ) {
var post = {
id: req.params.id,
name: req.params.name,
longUrl: req.params.longurl,
};
connection.query( "INSERT INTO `test` SET ?", post, ( error, rows ) => {
if( error ) throw error;
if( !error ) {
res.status( 200 ).send(rows);
}
} )
} );
答案1
得分: 0
前端部分:
encodeURIComponent(longUrl)
后端部分:
decodeURIComponent(longUrl)
英文:
I will try this front end:
encodeURIComponent(longUrl)
and back end:
decodeURIComponent(longUrl)
答案2
得分: 0
我解决了我的问题。 URL参数已更改为JSON对象。
新版本前端代码:
const ulozeniZmen = (event) => {
fetch('https://serverWithNodeApp.com/insert/',{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id: id, name: name, longurl: longurl
})
})
event.preventDefault();
}
新版本后端代码:
app.post('/insert/', function (req, res) {
let data = {id: req.body.id, name: req.body.name, longUrl: req.body.longurl};
connection.query("INSERT INTO `test` SET ?", data, (error) => {
if (error) throw error;
if (!error) {
res.status(200).send(rows);
}
})
});
英文:
I resolved my problem. Url params i was changed to Json object
New version code front-end:
const ulozeniZmen = (event) => {
fetch('https://serverWithNodeApp.com/insert/',{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id: id, name: name, longurl: longurl
})
})
event.preventDefault();
}
New version code back-end:
app.post( '/insert/', function ( req, res ) {
let data = {id: req.body.id, name: req.body.name, longUrl: req.body.longurl};
connection.query( "INSERT INTO `test` SET ?", data, ( error ) => {
if( error ) throw error;
if( !error ) {
res.status( 200 ).send(rows);
}
})
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论